Есть ли у Spring (boot) способ проверить, содержит ли запрос REST параметр, явно не объявленный вызываемым методом REST?
С помощью флага required мы можем принудительно установитьклиент для включения определенного параметра в запрос.Я ищу аналогичный способ запретить клиенту отправлять параметр, который не является явным, упомянутым в объявлении метода контроллера:
@RequestMapping("/hello")
public String hello(@RequestParam(value = "name") String name) {
//throw an exception if a REST client calls this method and
// sends a parameter with a name other than "name"
//otherwise run this method's logic
}
Например, вызов
curl "localhost:8080/hello?name=world&city=London"
долженрезультат в ответе 4xx .
Одним из вариантов будет явная проверка на неожиданные параметры:
@RequestMapping("/hello")
public String hello(@RequestParam Map<String,String> allRequestParams) {
//throw an exception if allRequestParams contains a key that we cannot process here
//otherwise run this method's logic
}
Но возможно ли достичь того же результата при сохранениитакое же удобное @RequestParam
использование, как в первом примере?
EDIT : Извините, я не вижу никакой связи с этим вопросом .Другой вопрос касается обработки аннотаций во время выполнения.Мой вопрос касается поведения REST-движка Spring.Я что-то упустил?
РЕДАКТИРОВАТЬ : На основе ответов я написал это HandlerInterceptor :
@Component
public class TooManyParamatersHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod m = (HandlerMethod) handler;
if (m.getMethod().getName().equals("error")) {
return true;
}
List<String> allowedParameters = Stream.of(m.getMethodParameters())
.flatMap(p -> Stream.of(p.getParameterAnnotation(RequestParam.class)))
.filter(Objects::nonNull)
.map(RequestParam::name).collect(Collectors.toList());
ArrayList<String> actualParameters = Collections.list(request.getParameterNames());
actualParameters.removeAll(allowedParameters);
if (!actualParameters.isEmpty()) {
throw new org.springframework.web.bind.ServletRequestBindingException(
"unexpected parameter: " + actualParameters);
}
return true;
}
}