Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL and c:when test condition

how can I check and use userLoggedIn to testify the condition. I am new and I have search alot. there must be a silly mistake.

index.jsp

<div id="sign-in">
    <c:choose> 
        <c:when test="${userLoggedIn == 1}"> 
             Welcome <c:out value="${loginID}" /> | Logout
        </c:when>
        <c:otherwise>Log-in</c:otherwise>
    </c:choose>
</div>

some verification servlet

int userLoggedIn = 0;

if(loginID.equals("[email protected]") && password.equals("guest")){
    userLoggedIn = 1;
    getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
    //     out.println("login successful");

} else {
    //   getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
    out.println("login failed");
}
like image 545
kevin Avatar asked Dec 27 '12 20:12

kevin


People also ask

What is c if test?

C if StatementIf the test expression is evaluated to true, statements inside the body of if are executed. If the test expression is evaluated to false, statements inside the body of if are not executed.

Can we use c if inside c otherwise?

The < c:otherwise > is also subtag of < choose > it follows &l;twhen > tags and runs only if all the prior condition evaluated is 'false'. The c:when and c:otherwise works like if-else statement. But it must be placed inside c:choose tag.

Which type of Java conditional statement is the c choose tag similar to?

The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives.

What is JSTL testing?

The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated is true. It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.


1 Answers

You need to store the information in the desired scope, which is usually the session scope for case of logged-in users.

Add the following line after userLoggedIn = 1;.

request.getSession().setAttribute("userLoggedIn", userLoggedIn);

That's basically all you need to change.


Unrelated to the concrete problem, this int (and boolean as commented by BevynQ) approach is rather "primitive". You'd usually store the entire User entity obtained from the DB in the session instead. E.g.

User user = userService.find(username, password);

if (user != null) {
    request.getSession().setAttribute("user", user);
    response.sendRedirect("home");
} else {
    request.setAttribute("message", "Unknown login, please try again");
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

with

<c:when test="${not empty user}">

which allows easy access of all its properties like

<p>Welcome, <c:out value="${user.name}" /></p>
like image 183
BalusC Avatar answered Oct 14 '22 01:10

BalusC