Spring Rest API - 假/未请求参数策略

时间:2017-12-07 15:20:03

标签: java rest validation spring-boot request

根据这个讨论 - "RESTful API - Correct behavior when spurious/not requested parameters are passed in the request",我们不应该忽略未请求的参数,而是如何在所有端点上处理这种情况?

例如,对于此端点:

@RequestMapping(value = "/transactions/",
        method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RestResultSupport getCommandsById(@PathVariable("id") String id) throws IOException {
    validateId(id);
    ....
    return result;
}

对于两个不同的请求,我们会得到相同的结果:

curl localhost:8080/?id=1200

curl localhost:8080/?id=1200&unknown=incorrect

如果我们想象我们应该在20个端点上处理这种情况,我们如何简化代码呢? Spring是否为此提供了一些工具?

1 个答案:

答案 0 :(得分:0)

我发现只有一种方法 - 实现HandlerInterceptor。

请看一个例​​子:

public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        Set<String> innerParams = request.getParameterMap().keySet();
        Set<String> describedParams = new HashSet<>();
        for (MethodParameter methodParameter : ((HandlerMethod) handler).getMethodParameters()) {
            if (methodParameter.hasParameterAnnotation(RequestParam.class)) {
                RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
                describedParams.add(requestParam.name());
            }
        }

        for (String inputRequestParam : innerParams) {
            if (!describedParams.contains(inputRequestParam)) {
                throw new BadDataException("Please provide valid request paramaters. [ Valid request parameters - " + describedParams + " ]");
            }
        }

        return true;
    }

... empty other required methods ...
}

代码分析所需的参数,如果它未知,它将抛出RuntimeException