简体   繁体   中英

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("guest@guest.com") && 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");
}

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. Eg

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM