I am having an issue with creating some JSP pages. I have a few pages (Home, About Us, Contact Us) done up in JSP, and I also have the ability to login to this site using a username and password.

What I want to achieve is to allow visitors to access the About Us and Contact Us page without logging in. Yet if the visitor has logged in, I want to print a simple welcome message in About Us and Contact Us that includes his username.

I am implementing the MVC architecture, so I already have the controller and model done. The code I have for the About Us page is:

<jsp:usebean id="user" type="UserBean" scope="session"/>
...other code...
Welcome, <jsp:getproperty name="user" property="username"/>

This displays fine if the user has already logged in, however it throws an exception if I access this page directly without logging in. I can fix the problem by changing the usebean line to:

<jsp:usebean id="user" class="UserBean"/>

But this doesn't seem in line with MVC, which says that I shouldn't let JSP pages create classes.

Is there any way to conditionally use the bean only if it exists? Or is this implementation wrong, and there is an alternative?

Recommended Answers

All 7 Replies

use JSP expression language and JSTL tag library

Correct me if I am wrong, but I believe the <jsp:usebean> tags are always executed when they are in the JSP page. There is no way to enclose them in a conditional if-else statement. Is this what you meant? Or is there another way using the "JSP expression language" that you mentioned?

the usebean tag just tells the page to use a bean of that class. It's a variable declaration, nothing else.

When using JSTL you don't need it. It's an outdated concept designed to be used with JSP tag libraries predating JSTL.

How will it look like in JSTL? Actually I have just started learning JSP for a project. I have Java background so it's been a little easier to learn JSP, but I'm still not too sure about some things.

Buy O'Reilly's JSP book (3rd edition or newer).
basically you get something like

<c:choose>
  <c:if condition="condition"> 
  </c:if>
  <c:if condition="condition2"> 
  </c:if>
  <c:otherwise>
  </c:otherwise>
</c:choose>

@jwenting you made a mistake. if tags are not valid inside choose tags; you need to replace the if tag with when tag

Buy O'Reilly's JSP book (3rd edition or newer).
basically you get something like

<c:choose>
  <c:if condition="condition"> 
  </c:if>
  <c:if condition="condition2"> 
  </c:if>
  <c:otherwise>
  </c:otherwise>
</c:choose>

So I will be able to put <jsp:usebean> statements in the condition part?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.