Additional path segments in Spring MVC

Reading this 2010 Spring article, it discusses the use of the extension to provide a convenient way to include optional path segments

@RequestMapping("/houses/[preview/][small/]{id}") public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) { return "view"; } 

I know that I could just implement several query mappings to achieve the same effect:

 @RequestMapping(value="/houses/preview/{id}") ... @RequestMapping(value="/houses/{id}") ... ~~~ snip ~~~ 

But depending on the number of possible permutations, this seems like a very detailed option.

Does any later version of Spring (after 3) provide such a tool? Alternatively, is there any mechanism to combine parts of the request URL to provide a larger signature of the response method?

Update

This answer to a question related to the exchange of path variables and query parameters, offers an approach such as:

 @RequestMapping(method=RequestMethod.GET, value={"/campaigns","/campaigns/{id}"}) @ResponseBody public String getCampaignDetails( @PathVariable("id") String id) { ~~~ snip ~~~ 

But the path variable cannot be set to null. Just going to /campaigns will return a 400 response.

+5
source share
1 answer

Why don't you use java.util.Optional if you use Java 1.8 . To take your later example, you can prevent the 400 response from using Optional<String> instead of String representing your eventualy path like this:

 @RequestMapping(method=RequestMethod.GET, value={"/campaigns","/campaigns/{id}"}) @ResponseBody public String getCampaignDetails( @PathVariable("id") Optional<String> id) { if(id.isPresent()){ model.addAttribute("id", id.get());//id.get() return your String path } } 
+8
source

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


All Articles