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

pik*_*ik4 2 java spring

我请求的路径是:

localhost:8080/companies/12/accounts/35
Run Code Online (Sandbox Code Playgroud)

我的 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
Run Code Online (Sandbox Code Playgroud)

是否有任何功能可用于在过滤器内接收此信息?

小智 7

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


jet*_* ma 6

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);  
String companyId = (String)pathVariables.get("companyId"); 
String accountId= (String)pathVariables.get("accountId");
Run Code Online (Sandbox Code Playgroud)

  • 这很有趣,但只是故事的一半。为了让您的答案起作用,过滤器必须已经调用了 `chain.doFilter(request, response);`。通常,http 过滤器需要在到达控制器之前做一些事情。所以虽然这个答案有一些优点,但@ambwa 有正确的答案。 (2认同)