javajspel

Define variables inside if condition in JSP


I am passing a value from a servlet to JSP using follows, which returns Integer value.

HttpSession session = request.getSession();
session.setAttribute(USER_OFFICE, user.getOffice().getId());

I can get this value in JSP:

<%=session.getAttribute("USER_OFFICE")%>

Now I need to show some text in JSP based on USER_OFFICE values:


Solution

  • Try EL & taglib:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <c:choose>
        <c:when test="${1 eq USER_OFFICE}">
           Hello Police
        </c:when>
        <c:when test="${2 eq USER_OFFICE}">
            Hello Doctor
        </c:when>
        <c:otherwise>
            Hello Engineer
        </c:otherwise>
    </c:choose>
    

    OR without taglib:

    ${1 eq USER_OFFICE ? "Hello Police" : (2 eq USER_OFFICE ? "Hello Doctor" : "Hello Engineer")}