6

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.

newbie
  • 14,582
  • 31
  • 104
  • 146
  • Hi @newbie, I'm having the same problem you got. Did you get a simple example of CRUD webapp and how to mapping url? I did /person/* mapping and now I have to parse /person/add/1, /person/del/1, /person/upd/1, /person/lst but I'm not sure how to apply the pattern or design. Thanks – Joe Mar 31 '13 at 20:15

2 Answers2

6

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.

  1. 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.

  2. 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.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You're welcome. Btw, regarding your user profile, do I really scold that often? Sorry about that. – BalusC Mar 10 '11 at 03:37
  • @BalusC: Your option 1 above "Just use 4 separate servlets" intrigues me. Like you said, with Servlet 3.0 annotations, you can easily map URLs to servlets. So each servlet would be like an action in struts or a controller in spring (or asp.net mvc). This would become a decent "framework". The servlets can be organized into a package hierarchy and each servlet would have a very specific responsibility. What major shortcomings would you see with this approach compared to a heavy framework (aside form the additional tools a framework provides)? – stepanian Mar 01 '12 at 02:07
  • @stepanian: MVC frameworks provides builtin facilities to collect request parameters, doing conversion/validation on it, invoking specific business actions, redisplaying submitted values and showing error messages. With plain vanilla servlets you'd still need to write pretty much boilerplate code to do the same and in the end you'd be tempted to refactor it all out to something common and reuseable with a minimum of code. But that's exactly what an existing MVC framework has already done for you. – BalusC Mar 01 '12 at 03:03
  • Thanks. For some reason, I like the "raw" effect associated with servlets and JDBC. By the way, you are an amazing resource on the web. I have learned more from your posts over the years than all the Sun/Oracle documentations. A sincere thanks from me! – stepanian Mar 01 '12 at 03:18
3

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

  • reads customer with id=1

DELETE http://www.example.com/customer/1

  • deletes customer with id=1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • How would you invoke it from JSP/HTML on? With a Servlet, right? – BalusC Mar 10 '11 at 03:28
  • @BalusC - A read (GET) is as simple as reading from the URL. If you enter the URL in a browser you will see the response. The other operations depend on JSP support for executing HTTP commands. The JAX-RS service can also be configured for JSON message which work quite well with JSP. – bdoughan Mar 10 '11 at 14:19
  • So you're recommending to replace Servlet by JavaScript/Ajax? How would you handle users which has JS disabled? Mobile browsers for example. – BalusC Mar 10 '11 at 14:24
  • @BalusC - I'm simply suggesting that the servlet that is interpreting the URLs to perform the CRUD operations be replaced by a JAX-RS service that is designed to interpret URLs and HTTP operations to perform CRUD operations. – bdoughan Mar 10 '11 at 14:56
  • Yes, but how would you invoke it from JSP/HTML on? It simply returns XML/JSON/whatever and not HTML. So it has to be transformed somehow. You can't simply have a `
    ` since it doesn't return HTML. And providing a full fledged HTML webpage-specific response by JAX-RS so that it can be displayed at once makes in turn no sense since it cannot be reused by others then.
    – BalusC Mar 10 '11 at 14:58
  • Check out the following about Jersey and MVC using Viewables: http://blogs.sun.com/sandoz/entry/mvcj – bdoughan Mar 10 '11 at 15:10
  • Interesting. Too bad that it's Jersey specific, not JAX-RS specific. – BalusC Mar 10 '11 at 15:18
  • The next version of the JAX-RS specification is currently being worked on. Hopefully it will be added then. – bdoughan Mar 10 '11 at 15:21