let’s say i have a servlet that forwards a request to a jsp file that contains a list of products.
for example, Login.java is a servlet that forwards a request (upon successful login) to Products.jsp.
now, in Products.jsp i have to check first that user is indeed logged in:
<% if (request.getSession().getAttribute("username") == null) {
response.sendRedirect("/store/login");
return;
} %>
this is in order to prevent the user from seeing the products just by writing localhost:8080/store/Products.jsp.
I read here some posts that it is best to avoid writing java code in jsp files.
so my question is, is there a more elegant way to solve this problem?
Yes – put all JSP files in
WEB-INF/(for example –WEB-INF/jsp), and only forward to them from servlets. For example, if a servlet is mapped to/foo, then itsdoGet()method can perform the logic you’ve written, and do the forward toproduct.jsp.It might become too verbose with bare servlets though, so a framework like Spring MVC can be very helpful.
Generally, authentication checks are preformed by a
Filterthough – you put a filter which checks each request and if a user is not authenticated, the filter redirects.