Spring Matrix variables require at least one template variable to work?

I am trying to get a simple REST API to display the contents of a collection, and I am using matrix variables to control pagination.

My controller has the following method for listing the contents of a collection:

@RequestMapping( value = "articles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ArticlePageRestApiResponse listArticles( @MatrixVariable(required = true, defaultValue = 100, value = "resultsPerPage") int resultsPerPage, @MatrixVariable(required = true, defaultValue = 0, value = "pageNumber") int pageNumber) { // some logic to return the collection } 

If I then do a GET http://example.com/articles;resultsPerPage=22;pageNumber=33 , it will not be able to find the display of the request. I have included support for matrix variables by adding the following:

 @Configuration public class EnableUriMatrixVariableSupport extends WebMvcConfigurationSupport { @Override @Bean public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping hm = super.requestMappingHandlerMapping(); hm.setRemoveSemicolonContent(false); return hm; } } 

I found that if matrix variables have a prefix with at least one template variable, then matrix variables are correctly assigned. The following works, but ugly, where I had to make part of the URI path a template variable, which would always be β€œarticles”, to trick the query matching handler into thinking that there was at least one URI template variable:

 @RequestMapping( value = "{articles}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ArticlePageRestApiResponse listArticles( @PathVariable("articles") String ignore, @MatrixVariable(required = true, defaultValue = 100, value = "resultsPerPage") int resultsPerPage, @MatrixVariable(required = true, defaultValue = 0, value = "pageNumber") int pageNumber) { // some logic to return the collection } 

I found an error or am I misunderstanding the matrix variables?

+4
source share
1 answer

According to Spring documentation

If the URL is expected to contain matrix variables, the pattern matching should represent them with the pattern URI. This ensures that the request can be correctly matched regardless of whether the matrix variables are present or not and in what order they are provided.

In the first example, you are not using templates (for example {articles}) to map URLs, so Spring cannot determine the matrix parameters. I would call it not a mistake, but a side effect. We only have this because @MatrixVariable support is built on top of the old @PathVariable parsing engine.

0
source

Source: https://habr.com/ru/post/1487175/


All Articles