I’m a beginner in JSP. While developing a web application for a sample scenario,
I came across this subtlety.
I have the following pages:
- index.jsp
- login.jsp (and LoginServlet.java)
- account.jsp
To facilitate code reuse I divided all pages into 3 parts – menu-header, content, footer.
For all the above pages, menu-header and footer remains the same, only the content changes.
So, I created menuandheader.jsp and footer.jsp to be included into every page.
index.jsp = (menuandheader.jsp+content+footer.jsp)
Now I have 5 different user roles thus, 5 different index and account pages. (again for these pages only the content area changes).
I created a Filter class for LoginServlet.java which takes care of authentication and stores the appropriate page name as a request attribute. (index1.jsp for role #1 and so on) Now the only contents of LoginServlet.java is
dispatch = request.getRequestDispatcher(request.getAttribute("page").toString());
dispatch.forward(request, response);
But in this approach I need to have 5 almost similar index and account pages. Is there a better way to deal with this scenario?
Let’s first look at the downsides of your approach
I would say a better approach would be to solve the problem on hand (i.e. restrict resource access based on user role). You can do this in many ways, Here is one way you could solve the problem
In index.jsp, you could do some thing like this, I used simple jstl tag in the example
I just gave you a simple approach to solve this problem, I would let you choose what the best option would be based on your requirement, I would say keep the implementation loosely coupled and easily extendable.