如何以 MVC 方式使用 PRG 实现命令模式



我正在使用tomcat,jsp,servlets和log4j进行我的第一个Web项目,并且我有一个使用命令设计模式的演示,对此我很感兴趣。我有一个控制器,它接受doGet和doPost方法,然后将请求处理到CommandContainer,该命令容器找到适当的命令,执行它,获取资源的路径并将客户端转发给它。

public abstract class Command implements Serializable { 
    private static final long serialVersionUID = 8879403039606311780L;
    public abstract String execute(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException;
}

管理命令的命令容器:

public class CommandContainer {
    private static final Logger LOG = Logger.getLogger(CommandContainer.class);
    private static Map<String, Command> commands = new TreeMap<String, Command>();
    static {
        // common commands
        commands.put("login", new LoginCommand());
        commands.put("logout", new LogoutCommand());
        commands.put("viewSettings", new ViewSettingsCommand());
        commands.put("noCommand", new NoCommand());
        // client commands
        commands.put("listMenu", new ListMenuCommand());
        // admin commands
        commands.put("listOrders", new ListOrdersCommand());
        LOG.debug("Command container was successfully initialized");
        LOG.trace("Number of commands --> " + commands.size());
    }
public static Command get(String commandName) {
    if (commandName == null || !commands.containsKey(commandName)) {
        LOG.trace("Command not found, name --> " + commandName);
        return commands.get("noCommand"); 
    }
    return commands.get(commandName);
}

我唯一的控制器:

public class Controller extends HttpServlet {
    private static final long serialVersionUID = 2423353715955164816L;
    private static final Logger LOG = Logger.getLogger(Controller.class);
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }
    private void process(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        LOG.debug("Controller starts");
        // extract command name from the request
        String commandName = request.getParameter("command");
        LOG.trace("Request parameter: command --> " + commandName);
        // obtain command object by its name
        Command command = CommandContainer.get(commandName);
        LOG.trace("Obtained command --> " + command);
        // execute command and get forward address
        String forward = command.execute(request, response);
        LOG.trace("Forward address --> " + forward);
        LOG.debug("Controller finished, now go to forward address --> " + forward);
        // if the forward address is not null go to the address
        if (forward != null) {
            RequestDispatcher disp = request.getRequestDispatcher(forward);
            disp.forward(request, response);
        }
    }
}

我正在以以下方式在 jsp 中使用控制器:

...
    <form id="login_form" action="controller" method="post">
                    <input type="hidden" name="command" value="login"/>
...
    </form>

和网络.xml文件:

<servlet>
    <servlet-name>Controller</servlet-name>
    <servlet-class>com.mycompany.web.Controller</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>/controller</url-pattern>
</servlet-mapping>

我不明白如何使用命令模式实现 Post-Redirect-Get 模式,因为每次请求到达控制器时,它都会使用process()方法,并且似乎在 JSP 中使用 GET 或 POST 并不重要。然后你能帮助理解使用命令模式的必要性吗?如果我使用多个servlet,如LoginServlet,LogoutServlet,ViewSettingsServlet而不是一个控制器怎么办 - 这将是一个坏主意,因为这样我需要将它们硬编码为jsp形式作为操作?所有这些问题都让我感到困惑,因为我是一个初学者,所以请让我理解这一切。

好吧,目前,您的命令返回一个字符串:要转发到的 JSP 的名称。如果我理解正确,您还希望能够重定向而不是转发。因此,您需要调用返回值的 servlet,如果不是要转发到的视图名称,而是要重定向到的 URL。

有多种方法可以做到这一点。例如,您可以返回一个对象,其中包含要执行的操作类型(FORWARD 或 REDIRECT)以及视图名称或 URL。或者你可以返回一个字符串,如 redirect:/foo/bar,这意味着/foo/bar 是要重定向到的 URL,而不是视图名称。

但最好的解决方案可能是避免重新发明轮子,并使用现有的 MVC 框架而不是自己实现一个:Spring MVC、Stripes、Struts 等都提供了比你那里拥有的更多的东西,而且方式要好得多。特别是,使用请求参数来选择命令不是一个非常好的选择。使用路径是一个更好的主意。

您也可以简单地使用多个 servlet,这将比您当前的解决方案更好。但是,您将丢失前端控制器,该控制器通常包含所有命令通用的代码:国际化,安全检查等。

最新更新