Spring MVC中的可选路径段 [英] Optional path segments in Spring MVC

查看:138
本文介绍了Spring MVC中的可选路径段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从2010年开始阅读这篇(春季3)文章,它讨论了如何使用扩展名来提供一种方便的方式来包含可选路径段:

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.

Spring的任何更高版本(3之后)是否提供这种功能?另外,是否有任何机制可以将请求URL的各个部分链接起来,以提供更大的响应方法签名?

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?

更新

此回答有关共享路径变量和请求参数的问题,建议采用以下方法:

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 ~~~

但是path变量不能设置为null.只需转到/campaigns,将返回400响应.

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

推荐答案

如果使用Java 1.8,为什么不使用java.util.Optional.以后面的示例为例,您可以通过放置Optional<String>而不是String来表示最终的路径来避免出现400响应,如下所示:

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
  }
}

这篇关于Spring MVC中的可选路径段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆