Spring MVC - How to check if unexpected query string parameters were passed?

I have a web service written in Spring MVC. It can be used by third-party developers. Our methods have many optional parameters (passed in the query string).

I want to make sure that all query string parameters are spelled correctly and that there are no typos. Is there an easy way to do this? Method signature example:

@RequestMapping(value = {"/filter"}, method = RequestMethod.GET) @ResponseBody public List<MetricType> getMetricTypes( @RequestParam(value = "subject", required = false) Long subjectId, @RequestParam(value = "area", required = false) Long areaId, @RequestParam(value = "onlyImmediateChildren", required = false) Boolean onlyImmediateChildren, @RequestParam(value = "componentGroup", required = false) Long componentGroupId ) throws Exception { //Some code } 

If someone calls this method the parameter "onlyImediateChildren = true" (typo) instead of "onlyImmediateChildren = true", Spring MVC will ignore the sealed parameter and suppose that "onlyImmediateChildren" is null. The developer will receive a slightly incorrect list of results and will not notice an error. Such problems can be widespread and difficult to diagnose. I want to check for sealed parameters in the query string to prevent such problems.

UPDATE

A list of actual parameters can be retrieved from the query string. Then it can be compared with a list of allowed parameters. If I copy the list of allowed parameters, it will duplicate the method signature. I wonder if it is easy to extract a list of allowed parameters from a method signature (for example, by annotating @RequestParam)?

Many thanks

Maksim

+7
source share
3 answers

You can implement your own HandlerInterceptor . In the preHandle method, you can get all the HandlerMethod parameters annotated with @RequestParameter. These will be all allowed parameters in the request.

+4
source

You can use the getParameterMap request method to get a Map all the presented parameters and check the keys from the list of all allowed parameters. You should be able to get the request object by simply adding it to the method signature, for example:

 public List<MetricType> getMetricTypes( HttpServletRequest request, @RequestParam(value = "subject", required = false) Long subjectId, ... ) throws Exception { 
+1
source

Spring will enter all query parameters present in the url string through an argument of type

@RequestParam Map<String,String> in your controller method, if present.

 @RequestMapping(value = "", method = RequestMethod.GET, produces = {"application/json"}) public HttpEntity<PagedResources<WebProductResource>> findAll(@RequestParam Map<String, String> allRequestParams){ ... 

}

Then you can check the card keys yourself. For an β€œadventurous” way to do this altogether, see my answer here: How to check spring RestController for unknown query parameters?

+1
source

All Articles