Good day!
I am planning to do a simple CRUD application. I am planning to make my add, edit, delete and view handled by one controller. Something like this:
@WebServlet(name="ControllerServlet",
urlPatterns = {"/add","/edit","/delete","/view"}
then just use this code in my controller:
String userPath = request.getServletPath();
if (userPath.equals("/add")) {
}
But I am not sure if this is a common practice. Anyway, I am wondering what is the best practice for this? What are the pros and cons of doing this instead of separating each controller?
Thank you in advance.
Frankly, the common practice is to adopt a MVC framework. Java EE 6 offers JSF 2.0 out the box as a component based MVC framework. CRUD is possible with a single bean and a single view. You can find a basic example in this answer. The sole controller is provided by JSF itself, the FacesServlet
. Other MVC frameworks follows less or more the same ideology.
If you don't want to adopt a MVC framework because you would like to learn JSP/Servlets first and/or your project won't go beyond a CRUD form, then it is hard to point out the "right" approach. At least, the use of multiple URL patterns and if/else statements is a poor sign. You have basically 2 options.
Just use 4 separate servlets. With Servlet 3.0 you don't need to fiddle with web.xml
anymore and it's really easy to add another servlet class. Each servlet class functions as an "action" class and each one has a clear responsibility.
Use a single servlet, but don't use multiple URL patterns and don't use if/else
blocks to determine the actions. Map it on a single URL pattern such as /action/*
or *.do
so that you can invoke it by URLs like action/create
, action/read
, etc or by create.do
, read.do
, etc. Then create an interface like follows
public interface Action {
void execute(HttpServletRequest request, HttpServletResponse response);
}
Implement all actions based on this interface, CreateAction
, ReadAction
, etc and have in your servlet a Map<String, Action>
which you fill as follows during init()
method:
actions.put("create", new CreateAction());
actions.put("read", new ReadAction());
// ...
And invoke it as follows (assuming an URL pattern of /action/*
is been used)
actions.get(request.getPathInfo().substring(1)).execute(request, response);
That's also how the average MVC framework works deep under the covers.
Have you considered doing this as a RESTful service using a JAX-RS framework (like Jersey)? Then you leverage URIs and the HTTP operations: PUT, GET, POST, DELETE for CRUD:
For example:
GET http://www.example.com/customer/1
DELETE http://www.example.com/customer/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With