2012-08-08 64 views
0

我目前正在使用傳統的Spring 2.5應用程序,我想要做的是修改自定義控制器(它擴展了SimpleFormController)驗證邏輯。Spring MVC-在onBindAndValidate中添加cookie

protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception; 

我想在這個方法裏面做的是根據我提供的服務類的結果寫一個cookie。然而,由於在控制器的內部工作流程這一點我沒有訪問HttpServletResponse對象,有沒有其他的辦法:

  • 要麼檢索HttpServletResponse對象一個cookie寫入。要麼。
  • 在Spring MVC中使用其他一些工具來生成一個cookie。我看過org.springframework.web.util.CookieGenerator,但它仍然需要響應對象才能工作。

我很感謝任何人都可以提供的幫助。

謝謝你的時間!

回答

0

事實證明,我仍然無法從Spring MVC 2.5中找到任何直觀的內置方法。

所以我最終做的是這個破解。首先我修改控制器調用效用函數類,將採取所得服務對象(無論它可被調用),它公開了一個小服務程序兼容getCookie()方法,然後放置到用戶的會話下,像這樣:

WebUtils.setSessionAttribute(request, "myResponseObjectSessionName", myResponseObject); 

現在,因爲它們都是從SimpleFormController繼承,我反而創造了一個新的抽象類,它仍從以前繼承,但修改handleRequestInternal()方法,像這樣:

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { 

    // let the controller do it's job 
    ModelAndView result = handleRequestInternal(request, response, errors); 

    // and then use a helper class to inspect the session, find the session attribute 
    // 'myResponseObjectSessionName', and set any cookies left in case it does exist at 
    // this point in time. 
    new ProcessServiceObject().setServiceResponseCookie(request, response); 

    return result; 
} 

不是很優雅,但我認爲它的工作原理。乾杯。

相關問題