Valery Valery - 4 months ago 23
Java Question

Spring tags instead java code

I'm looking for good example, how can I replace this java code with spring tags.

<%

Object user = (String) request.getSession().getAttribute("User");
Object role = (String) request.getSession().getAttribute("role");

if(user == null){
out.println("<a href=\"register.jsp\">Register</a> <a href=\"login.jsp\">Login</a>");
} else {
out.println(" Hello " + user +" "+"<a href=\"LogoutServlet\" >Logout</a>");
}
%>
</div>
<div class="menu">
<%
if (role != null){
if(role.equals("admin")) out.println("<a href=\"adminPanel.jsp\">Admin Panel</a></br>");
out.println("<a href=\"userOrders\">Orders</a></br>");
} else {
if(user != null) out.println("<a href=\"userOrders\">Orders</a></br></br>");
}%>

Answer

For this particular example core JSTL tags will suffice. However, please make sure that this weird conditional flow is what you expect.

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

<c:choose>
    <c:when test="${empty sessionScope.User}">
        <a href='register.jsp'>Register</a> 
        <a href='login.jsp'>Login</a>
    </c:when>
    <c:otherwise>
        Hello  <c:out value="sessionScope.User"/>
        <a href='LogoutServlet'>Logout</a>
    </c:otherwise>
</c:choose>
<div class="menu">
    <c:choose>
        <c:when test="${not empty sessionScope.role}">
            <c:if test="${sessionScope.role eq 'admin'}">
                <a href='adminPanel.jsp'>Admin Panel</a></br>
                <a href='userOrders'>Orders</a></br>
            </c:if>
        </c:when>
        <c:otherwise>
            <c:if test="${not empty sessionScope.User}">
                <a href='userOrders'>Orders</a></br></br>
            </c:if>
        </c:otherwise>  
    </c:choose>
</div>

Please note that ${not empty sessionScope.role} will evaluate to false in case of empty string. If this is not the desired behavior, use ${sessionScope.role != null}.

If you consider using Spring Security in your project, writing the similar things would be much easier and nicer with Spring Security taglib.

Comments