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.xmlanymore 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/elseblocks to determine the actions. Map it on a single URL pattern such as/action/*or*.doso that you can invoke it by URLs likeaction/create,action/read, etc or bycreate.do,read.do, etc. Then create an interface like followsImplement all actions based on this interface,
CreateAction,ReadAction, etc and have in your servlet aMap<String, Action>which you fill as follows duringinit()method:And invoke it as follows (assuming an URL pattern of
/action/*is been used)That’s also how the average MVC framework works deep under the covers.
See also: