DevGo
DevGo

Reputation: 1078

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:

Upvotes: 1

Views: 4591

Answers (3)

user2575725
user2575725

Reputation:

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")}

Upvotes: 3

gprathour
gprathour

Reputation: 15333

You can use scriptlet tag.

<%
    String value = session.getAttribute("USER_OFFICE");
    if(value.equals(1)){
           out.print("Hello Police");
    }else if(value.equals("2")){
           out.print("Hello Police");
    }else if(value.equals("3")){
           out.print("Hello Engineer");
    }

%>

P.S. You have mentioned 1, 2 and 3, which I didn't see earlier.

Upvotes: 0

atish shimpi
atish shimpi

Reputation: 5023

<%

String userOffice= session.getAttribute("USER_OFFICE")

if(userOffice.equals("1")){
   out.print("Hello Police")
}else if(userOffice.equals("2")){
  out.print("Hello Doctor")
}else if(userOffice.equals("3")){
  out.print("Hello Engineer")
}

%>

In this way you can write scriptlet in your JSP page.

Upvotes: 1

Related Questions