【问题标题】:Spring MVC - add cookie inside onBindAndValidateSpring MVC - 在 onBindAndValidate 中添加 cookie
【发布时间】:2012-08-05 06:17:45
【问题描述】:

我目前正在使用旧版 Spring 2.5 应用程序,我想做的是修改自定义控制器(扩展 SimpleFormController)的验证逻辑。

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

我想在这个方法中做的是根据我提供的服务类的结果编写一个 cookie。但是,由于此时在控制器的工作流程中我无权访问HttpServletResponse 对象,有没有其他方法可以:

  • 检索HttpServletResponse 对象以向其写入cookie。或者。
  • 使用 Spring MVC 中的一些其他工具来生成 cookie。我查看了org.springframework.web.util.CookieGenerator,但它仍然需要响应对象才能工作。

感谢任何人提供的帮助。

感谢您的宝贵时间!

【问题讨论】:

    标签: servlets cookies spring-mvc


    【解决方案1】:

    事实证明,我仍然无法在 Spring MVC 2.5 中找到任何直观的内置方法来执行此操作。

    所以我最终做的是这个 hack。首先,我修改了我的控制器以调用一个实用函数类,该类将获取生成的服务对象(无论它在哪里被调用),它公开了一个与 servlet 兼容的 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;
    }
    

    不是很优雅,但我认为它有效。干杯。

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 2017-04-15
      • 2014-05-31
      • 2012-06-16
      • 2012-11-22
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多