4

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Asher Saban
  • 4,673
  • 13
  • 47
  • 60

1 Answers1

4

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 its doGet() method can perform the logic you've written, and do the forward to product.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 Filter though - you put a filter which checks each request and if a user is not authenticated, the filter redirects.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140