如何在FilterRegistrationBean中获取@PathVariable?弹簧套



我请求的路径是:

localhost:8080/companies/12/accounts/35

我的Rest Controller包含这个函数,我想在Filter中获取companyId和accountId。

@RequestMapping(value = "/companies/{companyId}/accounts/{accountId}", method = RequestMethod.PUT)
public Response editCompanyAccount(@PathVariable("companyId") long companyId, @PathVariable("accountId") long accountId,
@RequestBody @Validated CompanyAccountDto companyAccountDto,
                                       HttpServletRequest req) throws ErrorException, InvalidKeySpecException, NoSuchAlgorithmException

有什么功能可以用来在过滤器内接收这些信息吗?

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);  
String companyId = (String)pathVariables.get("companyId"); 
String accountId= (String)pathVariables.get("accountId");

如果您引用的是Spring web过滤器链,则必须手动解析servlet请求中提供的URL。这是因为在实际控制器获取请求之前执行过滤器,然后执行映射。

更适合在Spring Filter(拦截器)中执行此操作。要存储检索到的值以便稍后在控制器或服务部分中使用,请考虑将Spring bean与Scope请求一起使用(request-Scope为单个HTTP请求创建一个bean实例)。下面的拦截器代码示例:

@Component
public class RequestInterceptor implements Filter {
    private final RequestData requestData;
    public RequestInterceptor(RequestInfo requestInfo) {
        this.requestInfo = requestInfo;
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //Get authorization
        var authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        //Get some path variables
        var pathVariables = request.getHttpServletMapping().getMatchValue();
        var partyId = pathVariables.substring(0, pathVariables.indexOf('/'));
        //Store in the scoped bean
        requestInfo.setPartyId(partyId);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

为了安全访问RequestData bean中的存储值,我建议始终使用ThreadLocal构造来保存托管值:

@Component
@Scope(value = "request", proxyMode =  ScopedProxyMode.TARGET_CLASS)
public class RequestData {
    private final ThreadLocal<String> partyId = new ThreadLocal<>();
    public String getPartyId() {
        return partyId.get();
    }
    public void setPartyId(String partyId) {
        this.partyId.set(partyId);
    }
}

通过添加Interceptor,它就可以工作了。问题的完整代码:https://stackoverflow.com/a/65503332/2131816

最新更新