如何在我的 java servlet 中实现“命令设计”。
什么是命令模式?
在面向对象的编程中,命令模式是一种行为设计模式,其中对象用于表示和封装以后调用方法所需的所有信息。此信息包括方法名称、拥有该方法的对象以及方法参数的值。
来源:wekipedia
要在您的案例 servlet 的 HttpServletRequest 操作参数是 home 和 add 中实现 Command Design Pattern,我正在考虑两个类似 删除、更新等
你说,
我的理解是每个 if 语句都应该转换为
具有执行函数的单独类,例如处理
添加对象。
好的,创建一个interface,执行方法返回类型为String,即视图名称。喜欢:
public interface Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception
}
为所有动作创建具体的动作类:
public class HomeAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//perform your home related action here..
return "home";
}
}
然后你说,
我捕获的错误被放入请求中并在我的 JSP 文件中使用。
所以实现添加动作类,如:
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";
}
}
}
更新和删除的相同实现,然后在您的 Servlet 中将所有操作保留在地图中,例如:
//Declare one map in your servlet to hold all concrete action objects.
private Map<String,Action> actionMap = new HashMap<String,Action>();
将所有动作对象放入构造函数中的actionMap或Servlet#init(ServletConfig config)中,例如:
actionMap.put("home", new HomeAction());
actionMap.put("add", new AddAction());
actionMap.put("update", new UpdateAction());
actionMap.put("delete", new DeleteAction());
在Servlet#service(HttpServletRequest request, HttpServletResponse response) 中执行没有if 和else 条件的操作
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..
}