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");
}
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.
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.
The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With