What is the Command Pattern? How can it be used with designing web applications using servlets and JSP?

Ryan Breidenbach

The Command Pattern is used to provide a common interface to execute different commands. A basic example of this would be:

public interface Command {
    public void execute();

Any class that implements this interface can provide specific impementation of a task in the execute() method:

public class SomeClass implements Command {
    public void execute() {

Now, other classes can be coded to the Command interface and not specific classes.

This pattern works well for designing web applications using JSP and servlets. A good way of doing this is to pass all JSP requests through a servlet. The servlet can then examine the request to determine what "action" needs to be taken, such as registering a user, purchasing a CD, etc. Based on that action, the servlet can instatiate an instance of a Command and call the execute method. This object will carry out the details of the action.

How the servlet determines what class to instantiate can be implemented in different ways. For example, this can part of the URL. So, if the URL was http://www.test.com/servlet/RegisterUser, the servlet may instatiate a RegisterUserCommand object and call execute. The RegisterUserCommand class could look like:

public class RegisterUserCommand implements Command {
    public execute() {
        registerUser(); //private method that registers the user
So, using the Command Pattern here isolates the processing to specific classes, while not tying the servlet to any of these specific classes, but rather the Command interface.