org.springframework.web.servlet.mvc.AbstractController 類別是Controller介面的簡單實作,使用Template Method模式實作了使用者的請求處理的流程,包括了對快取標頭(Caching header)的處理、檢驗對請求方法(GET、POST)的支援、Session的取得與同步化(synchronized)等,如果您需要對這些議題 作處理,則可以使用AbstractController類別。
AbstractController從handleRequest()方法被DispatcherServlet呼叫開始的工作流程如下所示:
- DispatcherServlet呼叫handleRequest()方法。
- 根據"supportedMethods"的設定來檢驗支援的請求方法,如果方法不支援則丟出ServletException。
- 根據"requireSession"的設定決定請求是否需要使用Session,嘗試取得Session,如果沒有取得Session則丟出ServletException。
- 根據"cacheSeconds"的設定決定是否設定快取標頭(Caching header)。
- 呼叫handleRequestInternal()方法,根據"synchronizeOnSession"的決定是否對Session進行同步化(synchronized)。
對於AbstractController類別的工作流程,您只要有個基本的了解就可以了,您可以直接繼承AbstractController類別,並重新定義它的handleRequestInternal()方法來實作請求的處理,例如:
public class SomeController extends AbstractController {
protected ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {
....
return new ModelAndView("view", "modelName", model);
}
..
}
protected ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {
....
return new ModelAndView("view", "modelName", model);
}
..
}
使用AbstractController類別的話,您可以直接操作它已經定義好的一些方法,例如您可以呼叫setSupportedMethods()方法,設定所允許的請求方式,例如Controller實作時若如下撰寫的話,則只支援POST的請求:
package onlyfun.caterpillar;
...
public class HelloController extends AbstractController {
...
public HelloController() {
this.setSupportedMethods(
new String[] {"GET", "POST", "HEAD"});
}
protected ModelAndView handleRequestInternal(
HttpServletRequest req,
HttpServletResponse res)
throws Exception {
...
}
}
...
public class HelloController extends AbstractController {
...
public HelloController() {
this.setSupportedMethods(
new String[] {"GET", "POST", "HEAD"});
}
protected ModelAndView handleRequestInternal(
HttpServletRequest req,
HttpServletResponse res)
throws Exception {
...
}
}
如果以不允許的方式請求的話,則Controller在處理的時候會丟出org.springframework.web.servlet.support.RequestMethodNotSupportedException的例外。