Reputation: 2895
I'm wondering what is the best practice in handeling servlets when dealing with a many pages in a website. Most GET requests in servlets simply return a new jsp page. I had thought of two approaches:
Assign a servlet for each path in the webiste e.g a homeservlet for home page, registerservlet for registration page, loginservlet for login page etc.
Have a small number of servlets that process multiple paths and handle them accordingly e.g. A UserServlet that could do the job of registration and logging in users. However I thought this approach might would just lead to lots of if statements and may be quite unmanageable. What would be ideal is assigning a method in a servlet to each path (similar to how Laravel does it)
Upvotes: 4
Views: 3144
Reputation: 2605
As it is often the case, what is best depends on the context and the functionality that must be offered. I would assume that in most cases allowing multiple paths to be handled from a single servlet would be more efficient as it allows the development of only one servlet for multiple cases. Mapping a group of paths to a single servlet would be preferable in the following cases:
However it could be the cases that assigning a single path per servlet would be beneficial:
Upvotes: 1
Reputation: 37
You can use joker character for mapping. For example;
*.jsp -> when client requested any jsp page, your servlet will be handle request.
Upvotes: -1
Reputation: 1063
Usually, I create a Servlet for each path. A colleague of me does it just the other way. I think it depends on your own preferences. I prefer my way because I can find the servlet I'm searching for way faster and your classes won't have lengths of thousands of LOC, so I think it's an aspect of clarity.
A benefit of your second approach is that you can call the methods in the same servlet more easily. Often, they are related to each other anyway! If your servlets are separated, you would have to forward the request to another servlet which - I think - would be less performant.
Another approach would be the Servlet Dispatching (also mentioned by @AdamSkywalker).
Upvotes: 1