4

I'm trying to understand how to implement the 'Command design' into my java servlet. Here is an example of the servlet:

protected void processRequest(HttpServletRequest ...) {

    String action = request.getParameter("action"); 
    String destination = null;

    } if (action.equals("Home")) 
        destination = "Home";
    } else if (action.equals("Add")) {
         String var = request...

         try {
            db.add(var);
         } (DatabaseException e) {
            request.setAttribute("errorMessage", e.getMessage());
         }
         ...
    }
 }

What I understand is that every if statement should be converted to a separate class with an execute function that handles for example the adding of an object. What I don't understand is how the requests are handles, are they handles in the execute function and from there returned to the Servlet/JSP (my catched errors are put in a request and used in my JSP files)?

I hope someone can give me a basic structure and show me how to begin implementing it.

2 Answers 2

10

how to implement the 'Command design' into my java servlet.

What is Command pattern?

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Source: wekipedia

To implement Command Design Pattern in your case servlet's HttpServletRequest action parameter are home & add, I am considering two more like delete, update, etc.

you said,

What I understand is that every if statement should be converted to a separate class with an execute function that handles for example the adding of an object.

ok, create one interface with execute method return type as String i.e. view name. like:

public interface Action {
   public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception
}

create concrete action classes for all action's like:

public class HomeAction implements Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
         //perform your home related action here..
         return "home";
    }
}

then you said,

my catched errors are put in a request and used in my JSP files.

so implement add action class like:

public class AddAction implements Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

         //get request parameters here..

         try {
               //perform add action which throws exception..
               return "success";
         }catch(DatabaseException e) {
               request.setAttribute("errorMessage", e.getMessage());// to show exception msg in jsp.
              //log exception to console or file here..
              return "failure";
         }
    }
}

Same implement for update & delete, then in your Servlet keep all action's in a map like:

//Declare one map in your servlet to hold all concrete action objects.
private Map<String,Action> actionMap = new HashMap<String,Action>();

Put all action objects into actionMap in constructor or in Servlet#init(ServletConfig config) like:

actionMap.put("home", new HomeAction());
actionMap.put("add", new AddAction());
actionMap.put("update", new UpdateAction());
actionMap.put("delete", new DeleteAction());

perform actions without if & else condition in Servlet#service(HttpServletRequest request, HttpServletResponse response)

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String actionKey = request.getParameter("action");
        Action action = actionMap.get(actionKey);
        String view = action.execute(request, response);

        //Here, if view is if failure then, forward to jsp, to available request attributes in jsp. 
        //      if view is success redirect to jsp..

}
Sign up to request clarification or add additional context in comments.

5 Comments

Look at return type of execute method of HomeAction and AddAction class.
Always use parametrized type such as private Map<String,Action> actionMap = new HashMap<String,Action>();. Avoid raw type.
Amazing, exactly what I was looking for!
A more beautiful implementation of the Command pattern in Servlets is Frontman, take a look bibeault.org/frontman
@Nestor Hernandez Loli, Do you have working link, because it is broken
2

You can create views as many as no of commands. for e.g. home.jsp, add.jsp etc.

Create a controller servlet that's sole purpose is to inspect the command and dispatch the corrected view based on command.

Basically I am talking about a very well known MVC [Model-View-Controller] pattern.

For more info have a look at Model–view–controller.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.