A More Modular Design Using Action Objects
The approach in Example 14.3 is to implement each action as a separate method in the servlet, so every time you add a new action, you also have to update the servlet. In a large application, you may find yourself adding more and more code to the controller servlet, eventually ending up with a class that’s hard to maintain.
A more modular approach is to treat each action as a separate class
that implements a common interface, for instance called
Action.[6] The
Action
interface may look like this:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public interface Action {
public void perform(HttpServlet servlet,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException;
}The single method, perform( )
, has
arguments that give the action class access to all the same objects
as a regular servlet: the request and
response objects. In addition, the
servlet argument lets the action class access the
servlet context and servlet configuration objects if needed.
With this approach, each action ends up as a simple class. For instance, the logout action is handled by a nice little class like this:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LogoutAction implements Action { public void perform(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession( ); session.invalidate( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access