Detail the method of Spring routing according to URL parameters

  • 2020-12-07 04:02:29
  • OfStack

preface

This paper mainly introduces Spring routing according to URL parameters, and shares it for your reference and learning value. Let's start with 1 to see the detailed introduction.

Found the problem

Recently, I found a problem when I was writing the interface. The path part of URL of the two REST interfaces is the same, which is distinguished by the different parameters passed in by query.

For example, S3 common upload interface is:


PUT /{bucketname}/{ objectname}

The interface for block uploading is:


PUT /{bucketname}/{objectname}?partNumber={partNumber}&uploadId={uploadId}

When you pass in partNumber and uploadId, it's one interface. If you don't pass in these two parameters, it's another interface. So how do you route in Spring?

Generally, we set up all the routes @RequestMapping(value = "/xx", method = RequestMethod.GET) . Parameters can then be injected in the method signature via @RequestParam.

But it is not possible to differentiate directly 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 method

The solution

This means duplicate registration, so @RequestParam cannot be used as a routing basis.

@RequestParam

Used to handle Content-ES46en: The content encoded for application/ ES48en-ES49en-ES50en-ES51en. (In the Http protocol, if Content-ES54en is not specified, the default parameter passed is of type application/ ES56en-ES57en-ES58en-ES59en)

RequestParam can accept properties of simple types as well as object types.

The essence is to convert the Key-ES69en parameter Map in ES66en.getParameter () into the parameter receiving object or field by using the conversion mechanism ConversionService configuration.

As a routing annotation, @RequestMapping provides the params parameter in addition to the common value field used to set url, specifying how to match the parameters of query in url. Several configuration methods:

myParam=myValue matches the myParam parameter and is equal to url of myValue myParam! =myValue matches the myParam parameter and is not equal to url of myValue myParam matches url with the myParam parameter ! myParam matches url without the myParam parameter

This gives you the flexibility to specify routes.

And @RequestMapping also provides the headers parameter, which allows us to route based on Header!

conclusion


Related articles: