我已经向MockMvc添加了一些过滤器以进行junit测试。这些过滤器之一具有@WebFilter批注。它旨在拦截URL,例如“ / third / *”。但是,当我尝试访问与上述模式不匹配的URL时,@ WebFilter注释不起作用。
ThirdAppFilter
@Component
@Order(value = 4)
@ServletComponentScan(basePackages = {"com.oppo.it.teambition.filter"})
@WebFilter(urlPatterns = { "/third/*" }, filterName = "thirdAppFilter")
@ConfigurationProperties(prefix = "whitelist")
@EnableConfigurationProperties
public class ThirdAppFilter implements Filter {
@Autowired
private UserService userService;
@Autowired
private ConfigCenter configCenter;
private Map<String, List<String>> ip;
@Value("${teambition.admin}")
private String adminAccount;
public void setIp(Map<String, List<String>> ip) {
this.ip = ip;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestAddress = request.getHeader("x-forwarded-host");
// 仅接受来自白名单ip的请求
// 来自网关的请求
List<String> gateways = configCenter.getWhitelistIpGateway() != null ? configCenter.getWhitelistIpGateway() : ip.get("gateway");
if (!gateways.contains(requestAddress)) {
response.sendError(HttpStatus.FORBIDDEN.value(), "访问者受限");
return;
}
String appTag = request.getHeader("userId");
String adminToken = userService.getUserToken(adminAccount, "@oppo.com");
request.setAttribute("appTag", appTag);
request.setAttribute("accessToken", adminToken);
request.setAttribute("adminToken", adminToken);
chain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
MockMvc
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(wac)
.addFilter(advanceFilter)
.addFilter(thirdAppFilter)
.addFilter(idempotenceFilter)
.addFilter(webhookFilter)
.build();
}