如何在 Spring 过滤器中获取路径变量? [英] How to get Path Variables in Spring Filter?

查看:65
本文介绍了如何在 Spring 过滤器中获取路径变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个安全过滤器,它需要根据路径变量的值进行一些检查.我试图这样做:

I am working on a security filter that needs to do some checks based on the value of the path variable. I was trying to do smth like this:

final MappathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

但地图总是空的,看起来我的过滤器比在请求中填充 URI_TEMPLATE_VARIABLES_ATTRIBUTE 属性的 RequestMappingHandlerMapping 具有更高的优先级.

But the map is always empty, it looks like my filter has higher precedence than the RequestMappingHandlerMapping that is populating URI_TEMPLATE_VARIABLES_ATTRIBUTE attribute in request.

我尝试添加以下配置:

@Configuration
@EnableWebMvc
public class WebConfiguration {

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping requestMappingHandler = new RequestMappingHandlerMapping();
        requestMappingHandler.setOrder(0);
        return requestMappingHandler;
    }
}

它没有帮助,过滤器在 RequestMappingHandlerMapping 被调用之前执行.

It doesn't help, filters are executed prior to RequestMappingHandlerMapping gets called.

相对路径示例:/user/{uid}/action

我的控制器中有几个路径.它们都在路径中具有 uid 路径变量,但有些路径的设置顺序不同,有些路径有 1 个以上的变量.

I have several paths in my controller. All of them have uid path var in the path, but some paths have them set not in the same order, some paths have more than 1 variable.

在我的安全过滤器中,我获取 Auth 标头,对其进行解密,从中获取 userId 并将其与路径 var 值进行比较.如果这些 ID 不匹配,我将返回 403.

In my security filter I fetch Auth header, decrypt it, fetch userId from it and compare it with path var value. If those ids do not match I return 403.

我想知道是否可以覆盖这两个操作的顺序.或者,也许还有其他方法可以检查过滤器中的路径变量?

I am wondering if it is possible to override the order of those 2 actions. Or, maybe, there is some other way of inspecting path variables in filters?

推荐答案

在 Spring 中,过滤器在 Servlet 之前执行.并且RequestMappingHandlerMappingDispatcherServlet 调用,所以RequestMappingHandlerMapping 不能用于检索Filter 中的路径变量.所以,我想要么实现拦截器,要么采用 AOP 方法.

In Spring, Filters are executed before Servlets. And RequestMappingHandlerMapping is called by DispatcherServlet, so RequestMappingHandlerMapping cannot be used to retrieve path vars in the Filter. So, I am thinking to either have an Interceptor implemented or go with AOP approach.

这篇关于如何在 Spring 过滤器中获取路径变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆