【问题标题】:How can I inject HttpServletRequest attributes (set in interceptor) in my controller?如何在我的控制器中注入 HttpServletRequest 属性(在拦截器中设置)?
【发布时间】:2017-07-14 06:00:04
【问题描述】:

我想在所有请求到达控制器之前为其添加一个属性。

我正在使用什么:

@Component
public class SessionValidatorInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    .... some code ....
    request.setAttribute("validRequest","true");
    .... more code ...
    return true;
}

现在要在我正在做的休息控制器中获取此属性:

public ResponseEntity<?> someMethod(HttpServletRequest request){
    request.getAttribute("validSession");
    ...

我的问题是我可以像 @RequestParam("validSession") 或 @PathVariable 或其他什么更优雅地做到这一点吗? Spring 可以为我做到这一点吗?

感谢任何帮助。

【问题讨论】:

  • @RequestAttribute 怎么样(从 Spring 4.3 开始可用)。
  • 哇。我有多愚蠢?谢谢@M.Deinum。请作为答案发布,以便我接受。 :)

标签: spring rest spring-mvc spring-boot


【解决方案1】:

在 Spring 4.3 中,为此添加了 @RequestAttribute 注释。

public void yourMethod(@RequestAttribute("validRequest") boolean valid)

类似的东西应该可以解决问题。

如果您使用的是 Spring 的早期版本,您可以实现自己的 HandlerMethodArgumentResolver 来做同样的事情。

【讨论】:

  • 谢谢。我正在使用当前的春季版本,所以它就像一个魅力! :)
【解决方案2】:

只需使用@RequestAttribute 像这样

public ResponseEntity<?> someMethod(HttpServletRequest request,
@RequestAttribute("validSession") String xyz){
}

既然Denim 先生没有发布答案,我想为什么不是我。 ^_^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2021-02-11
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多