简体   繁体   中英

Optional path segments in Spring MVC

Reading this (Spring 3) article from 2010, it discusses using an 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 I could just implement a number of request mappings to achieve the same effect:

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

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

But depending on the number of possible permutations, it seems like a very verbose option.

Does any later version of Spring (after 3) provide such a facility? Alternatively, is there any mechanism to chain portions of the request URL to feed a larger response method signature?

Update

This answer to a question relating to sharing path variables and request parameters suggests an approach like:

@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.

Why you don't use java.util.Optional if you are using Java 1.8 . To take your later example, you can avert a 400 response with put a 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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM