Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding dot-separated Strings with @PathVariable in Spring MVC

I have the following method in my controller:

@RequestMapping( value="/servers/{server}", method = RequestMethod.GET )
public @ResponseBody List<Application> getServerInformation( String server ) {
    logger.debug( "Request for server: " + server );
    ...
}

When I request /servers/test.myserver.com, the bound variable has value test.myserver. In general, for any request that includes dot-separated values the last part is omitted from the bound variable's value. I am using Spring 3.0.4

Any suggestions?

Thanks

like image 725
xpapad Avatar asked Jan 10 '12 13:01

xpapad


People also ask

What is the purpose of @PathVariable annotation in Spring MVC?

The @PathVariable annotation is used to extract the value from the URI. It is most suitable for the RESTful web service where the URL contains some value. Spring MVC allows us to use multiple @PathVariable annotations in the same method. A path variable is a critical part of creating rest resources.

What does the annotation @PathVariable do?

Simply put, the @PathVariable annotation can be used to handle template variables in the request URI mapping, and set them as method parameters.

What is @PathVariable Spring boot with example?

With the @PathVariable annotation, we bind the request URL template path variable to the method variable. For instance, with the /July/28/ URL, the July value is bind to the name variable, and 28 value to the age variable. var msg = String.

Is PathVariable required by default?

7. @PathVariable variables are required by default. Below @GetMapping method handles multiple request paths, but the @PathVariable are required by default, which means if we access the request path /api2/page/ , Spring will return an HTTP 500 server error code and also error message like missing URI template variable.


2 Answers

You can use Ant style matching patterns. For your example you can simply do this:

@RequestMapping( value="/servers/{server:.*}", method = RequestMethod.GET )
public @ResponseBody List<Application> getServerInformation(
                          @PathVariable(value = "server") String server ) {
    logger.debug( "Request for server: " + server );
    ...
}
like image 188
aweigold Avatar answered Oct 03 '22 08:10

aweigold


You may want to change the useDefaultSuffixPattern of DefaultAnnotationHandlerMapping. Check How to change Spring MVC's behavior in handling url 'dot' character for a discussion on this.

like image 23
Aravind A Avatar answered Oct 03 '22 08:10

Aravind A