首先與在servlet HttpServletResponse的處理,我使用的命令模式與此接口佰:有使用命令模式
public CommandResponse execute(HttpServletRequest req)
throws CommandException;
這是我服務的方法:
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
Command cmd = lookupCommand(req.getParameter("cmd"));
CommandResponse next = cmd.execute(req, res);
CommandToken.set(req);
if (next != null) {
if (!req.getHeader("X-Requested-With").equals("XMLHttpRequest")) {
if (next.isRedirect()) {
redirect(next, res);
} else if (next.isForward()) {
forward(next, req, res);
}
} else {
ajaxCall(next, res);
}
}
} catch (CommandException e) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
}
}
正如你可以看到我的服務方法對待重定向和轉發的邏輯,我的接口沒有訪問HttpServletResponse對象。但對於我的servlet的某些操作,我需要處理響應以添加一些內容,如xml或cookie。實現了更明顯的方法是修改我的界面:
public CommandResponse execute(HttpServletRequest req, HttpServletResponse res)
throws CommandException;
現在的問題:
1)在我看來上述解決方案將破壞代碼的elengacy和安全性,因爲我現在的行動有權訪問響應,並可以重定向和轉發,甚至可以將內容添加到響應中,並讓服務方法使用sendRedirect,但我們知道這將不起作用。我對嗎?爲了解決這個我這樣做:
public class CommandResponse {
private boolean redirect;
private boolean forward;
private String page;
private String contentType;
private String outContent;
private HashMap headers;
private List<Cookie> cookies;
...
public void mapToResponse(HttpServletResponse res) {
...
}
}
也就是說,我創建了一個僞造的響應,當我回來的動作的執行方法,我映射這個僞造應對真正的HTTP響應(只是如果我有一個正向或ajax調用)。
2-)那好?這說得通?我不應該使用它嗎?
3-)有更好的方法嗎?
謝謝。
一般來說Command模式,我會說,使用像JAX-RS或Spring MVC的框架幾乎總是比手寫servlet邏輯更好。 – chrylis
是的,但是一個大學項目,我不能使用一個。其實,我想了解更多關於我可以使用的可能模式, –