2012-08-08 61 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; 
} 

不是很优雅,但我认为它的工作原理。干杯。