0

If I had something like this:

<%
    String name =  (String)session.getAttribute("username");

    if(name!=null)
{%>

    <div id="navBar">
            <h2><a href="blah.jsp">Home</a>   |   
        <a href="blah1.jsp">SomewhereElse</a>   |  
    </div>
<%}%>

Basically, if variable name is null, don't display navigation bar, but since mixing Java and HTML should be avoided - I can't see how you can rewrite this to separate the 2 languages???

Steve
  • 61
  • 1
  • 6

3 Answers3

2

Use taglibs/EL. Your particular example can be solved as follows with help of JSTL <c:if>:

<c:if test="${not empty username}">
    <div id="navBar">
        <h2><a href="blah.jsp">Home</a>   |   
        <a href="blah1.jsp">SomewhereElse</a>   |  
    </div>
</c:if>

The given HTML will only be printed when there's no attribute with the name username in any of the page, request, session or application scopes.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

You should have a controller (it could be something simple as a plain Java servlet). You would send it to different JSP pages in one case or the other.

// controller
String jsp = "";
boolean userLoggedIn = isUserLoggedId();
if (userLoggedIn) {
   jsp = "logged_in.jsp";
} else {
   jsp = "not_logged_in.jsp";
}
getServletContext().
       getRequestDispatcher(jsp).forward(req, res);

JSP is not like PHP where you "invoke the file" directly. Instead, you should map a URL to a Servlet (controller) and then let that servlet handle internally the JSP part. Do remember to put JSP files in WEB-INF directory so user won't have direct access to it.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • So if the code I posted was say in home.jsp - you're suggesting that I should create a homeloggedin.html and homeloggedout.html? – Steve Feb 08 '11 at 19:47
0

I agree with BalusC.

Don't forget to add the following taglib directive:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

This allows you to reference the JSTL core tag library tags

This gives you a lot or useful features like if, choose, foreach, etc

Note that the taglib directive can be added indirectly through another jsp which is included by the current file.

E.g using:

<%@ include file="MyJspTagIncludeFile.jsp" %>
chrisp7575
  • 853
  • 5
  • 3