开发者

JSP - separating Java from HTML

开发者 https://www.devze.com 2023-02-09 13:52 出处:网络
If I had something l开发者_开发技巧ike this: <% String name =(String)session.getAttribute(\"username\");

If I had something l开发者_开发技巧ike 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???


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:

  • How to avoid Java code in JSP files?
  • JSTL tag info page
  • EL tag info page


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.


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" %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号