java – RequestHeader Spring Boot上的自定义验证

前端之家收集整理的这篇文章主要介绍了java – RequestHeader Spring Boot上的自定义验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我目前有这个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

但是我想对header属性进行一些自定义验证,即

if (!API_KEY_LIST.contains(apiKeyHeader)) {
    throw Exception();
}
最佳答案
执行此操作的最佳方法IMO是使用自定义注释@Segment创建自定义HandlerMethodArgumentResolver,看起来像这样:

public 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
原文链接:https://www.f2er.com/spring/432573.html

猜你在找的Spring相关文章