Java前端控制器

use*_*865 6 jsp servlets front-controller java-ee

我正在考虑在我的J2EE应用程序中实现Front Controller.您能否提供相同的链接(包含源代码示例)和任何标准?

最好的祝福

Bal*_*usC 15

首先,创建一个Servlet侦听某个url-pattern,例如/pages/*.落实service()查找与请求方法(相关联的操作方法GET,POST(后servlet的网址的一部分,等等)和PATHINFO url-pattern).

基本示例:

protected void service(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException {
  View view = new View(request, response);
  Action action = ActionFactory.getAction(request);
  action.execute(view);
  view.navigate();
}
Run Code Online (Sandbox Code Playgroud)

Action接口应该代表工作的一个单元.您可以实现它来执行必要的业务逻辑:

public interface Action {
  void execute(View view);
}
Run Code Online (Sandbox Code Playgroud)

ActionFactory应保持执行的类Action中的排序Map<String, Action>,其中String键表示请求方法和PATHINFO的更少或更多的组合.然后你可以得到Action如下:

public static Action getAction(HttpServletRequest request) {
  return actions.get(request.getMethod() + request.getPathInfo());
}
Run Code Online (Sandbox Code Playgroud)

View应代表的请求范围方面其Action可以工作.在navigate()你可以将请求转发给JSP显示:

public void navigate() {
  String path = "/WEB-INF" + request.getPathInfo() + ".jsp";
  request.getRequestDispatcher(path).forward(request, response);
}
Run Code Online (Sandbox Code Playgroud)

这应该让你开始(注意我留下了所有明显的检查,如空指针,以使示例不那么混乱,这取决于你现在).

然而,在整个故事中需要考虑更多,例如验证,转换,事件处理,输入值映射,本地化,依赖注入等.这一切都是相当重要的.更好的MVC框架将大部分内容都考虑在内,例如Sun JSF,Apache Struts,Spring MVC,Stripes等.如果你从来没有做过任何一个,那么我强烈建议你在养成一个之前这样做,否则你最终会浪费时间.