简体   繁体   English

Spring GET 方法如何在 controller 中的未知请求参数时引发异常

[英]Spring GET method how to raise Exception if an unknown request param in controller

So I have in my controller a GET method with optional request params:所以我在我的 controller 中有一个带有可选请求参数的 GET 方法:

@GetMapping(path = "/users/search")
    public @ResponseBody ResponseEntity<List<User>> getUserLike(
      @RequestParam(name = "id", required = false) Long id,
      @RequestParam(name = "name", required = false) String name,
      @RequestParam(name = "dateofbirth", required = false) @DateTimeFormat(pattern = "dd-MM-yyyy") LocalDate dateOfBirth
    ) {
      return userService.getUserLike(id, name, dateOfBirth);
    }

When I try to call this request with unknown parameters当我尝试使用未知参数调用此请求时

/users/search?id=1&myunknownparam=unknownParam

I'd like to raise an Exception when request has unknown param such as myunknownparam here.当请求具有未知参数(例如此处的myunknownparam )时,我想引发异常。

Though for now as all my parameters are optional my service returns the same result as it would with all the parameters set to null.虽然目前我的所有参数都是可选的,但我的服务返回的结果与将所有参数设置为 null 时的结果相同。

Query param are often optional, so it's rare that a server could reject you because of that.查询参数通常是可选的,因此服务器很少会因此拒绝您。
But what you are trying to achieve can be implemented with an Interceptor, you need some reflection to get the parameters of your method and verify that each client param is defined on the signature of your method.但是您尝试实现的目标可以使用拦截器来实现,您需要一些反射来获取方法的参数并验证每个客户端参数是否定义在方法的签名上。

Something like:就像是:

@Component
public class QueryParamInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) {
        Map<String, String[]> clientRequestParameters = request.getParameterMap();
        MethodParameter[] methodParameters = ((HandlerMethod) handler).getMethodParameters();
        List<String> definedMethodsParameters = Arrays.stream(methodParameters)
                .flatMap(methodParameter -> Arrays.stream(methodParameter.getParameterAnnotations()))
                .filter(annotation -> annotation.annotationType().isAssignableFrom(RequestParam.class))
                .map(annotation -> ((RequestParam) annotation).name())
                .collect(Collectors.toList());

        for (String clientRequestParameterKey : clientRequestParameters.keySet()) {
            if (!definedMethodsParameters.contains(clientRequestParameterKey)) {
                throw new IllegalArgumentException("The parameter " + clientRequestParameterKey + " passed by the client is unknown");
            }
        }
        return true;
    }
}

Note that an interceptor will be called at each request.请注意,每个请求都会调用一个拦截器。 So I would not use that in production due to the high cost of object introspection..所以我不会在生产中使用它,因为 object 内省的成本很高。

@GetMapping(path = "/users/search")
public @ResponseBody
ResponseEntity<List<User>> getUserLike(
        @RequestParam Map<String, String> allParams,
        @RequestParam(name = "id", required = false) Long id,
        @RequestParam(name = "name", required = false) String name,
        @RequestParam(name = "dateofbirth", required = false) @DateTimeFormat(pattern = "dd-MM-yyyy") LocalDate dateOfBirth
) {
    // here check if allParams contains only valid keys
    return userService.getUserLike(id, name, dateOfBirth);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在对Spring Boot Controller的GET请求中接受LocalDateTime参数? - How to accept LocalDateTime param in a GET request to Spring Boot Controller? 如何在弹簧mvc方法中获得参数? - how to get param in method post spring mvc? 为什么当我通过 AJAX GET 请求将“è”字符发送到 Spring MVC 控制器方法的输入参数时,它到达错误? - Why when I send the "è" character through an AJAX GET Request to an input param of a Spring MVC controller method it arrives wrong? Spring Boot Controller不支持请求方法&#39;GET&#39; - Request method 'GET' not supported in Spring Boot Controller Spring Controller覆盖@ModelAttribute请求参数映射 - Spring Controller override @ModelAttribute request param mapping 如何接受 object 数组作为 Spring 中的请求参数获取 API - How to accept an array of object as request param in Spring Get API 在调用控制器之前,如何在Spring中将一个请求参数转换为几个请求参数? - How to convert one request param into several request params in Spring before calling a controller? 如何将请求发送到后端 spring rest controller 与 Z466DEEC76ECDF324554 请求文件正文和请求 param - How to send request to backend spring rest controller with a json requestbody and request param as a multipart image file 春天如何基于方法参数从yaml文件中获取价值? - How get value from yaml file based on method param in spring? 如何使用Spring Controller获取请求URL? - How to get request url using spring controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM