Preface
This article mainly introduces the relevant content about Spring routing based on URL parameters. It is shared for your reference and learning value. Let’s take a look at the detailed introduction below.
Discover problems
Recently, I found a problem when writing interfaces, that is, the path parts of the URLs of the two REST interfaces are the same, and they are distinguished according to the query passing in different parameters.
For example, the normal upload interface of S3 is:
PUT /{bucketname}/{ objectname}The interface for uploading in chunks is:
PUT /{bucketname}/{objectname}?partNumber={partNumber}&uploadId={uploadId}The partNumber and uploadId are one interface, and the two parameters are not passed in are another interface. So how to set the route in Spring?
Generally, we set the routes @RequestMapping(value = "/xx", method = RequestMethod.GET) . Then in the method signature, parameters can be injected through @RequestParam.
However, it is not possible to directly implement distinction by injecting different parameters, such as:
@ResponseBody@RequestMapping(value = "/xx", method = RequestMethod.GET)public String get1(){ return "get1";}@ResponseBody@RequestMapping(value = "/xx", method = RequestMethod.GET)public String get2(@RequestParam name){ return "get2" + name;}This will report an error:
java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'DemoController_v01' method public java.lang.String com.nd.sdp.ndss.controller.v01.DemoController.get1()to {[/demo/xx],methods=[GET]}: There is already 'DemoController_v01' bean methodSolution
It means that you have registered repeatedly, so @RequestParam cannot be used as a routing basis.
@RequestParam
Used to process Content-Type: content encoded for application/x-www-form-urlencoded. (In the Http protocol, if Content-Type is not specified, the default passed parameter is the application/x-www-form-urlencoded type)
RequestParam can accept properties of simple types or object types.
The essence is to use Spring's conversion mechanism ConversionService to configure the Key-Value parameter Map in Request.getParameter() to convert it into a parameter receiving object or field.
@RequestMapping is a routing annotation. In addition to the commonly used value field for setting the url, it also provides a params parameter, which can specify how to match the parameters of query in the url. Several configuration methods:
This allows you to specify routes very flexibly.
Moreover, @RequestMapping also provides the headers parameter, which allows us to route according to the header situation!
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.