jn025
jn025

Reputation: 2895

One Servlet per path or handle multiple paths in a Servlet?

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:

Upvotes: 4

Views: 3144

Answers (3)

Spyros K
Spyros K

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:

  1. The functionality offered by the group of paths is "similar" and can be handled by a single servlet, perhaps by taking in consideration the actual path.
  2. The functionality that should be offered is indifferent for the actual path that has been used to call the servlet.

However it could be the cases that assigning a single path per servlet would be beneficial:

  1. The functionality of a servlet should be offered by a single path only.
  2. The functionalities of different paths are different enough to require a different Servlet class to implement them.

Upvotes: 1

Alican Akkuş
Alican Akkuş

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

emmics
emmics

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

Related Questions