我目前有这个Request Mapper,我正在使用REGEX对Request Param进行验证.
@RequestMapping(value = "/example/{id}",method = GET)
public Response getExample(
@PathVariable("id") String id,@RequestParam(value = "myParam",required = true) @Valid @Pattern(regexp = MY_REGEX) String myParamRequest,@RequestParam(value = "callback",required = false) String callback,@RequestHeader(value = "X-API-Key",required = true) String apiKeyHeader) {
// Stuff here...
}
所以我能够用一种模式进行验证:
@RequestHeader(value = "X-API-Key",required = true) @Valid @Pattern(regexp = SEGMENTS_REGEX) String apiKeyHeader
if (!API_KEY_LIST.contains(apiKeyHeader)) {
throw Exception();
}
最佳答案
执行此操作的最佳方法IMO是使用自定义注释@Segment创建自定义HandlerMethodArgumentResolver,看起来像这样:
原文链接:https://www.f2er.com/spring/432573.htmlpublic class SegmentHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(String.class)
&& parameter.getParameterAnnotation(Segment.class);
}
@Override
public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer mavContainer,NativeWebRequest webRequest,WebDataBinderFactory binderFactory) throws Exception {
String apiKey = webRequest.getHeader("X-API-Key");
if (apiKey != null) {
if (!API_KEY_LIST.contains(apiKey)) {
throw new InvalidApiKeyException();
}
return apiKey;
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
然后您的控制器签名如下所示:
@RequestMapping(value = "/example/{id}",@Segment String apiKeyHeader) {
// Stuff here...
}
您将在WebMvcConfigurationAdapter中注册处理程序方法参数解析程序:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List