使用Spring的@RequestMapping和通配符 [英] Using Spring's @RequestMapping with wildcards

查看:1074
本文介绍了使用Spring的@RequestMapping和通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于此问题,但是我对自己的处境仍然感到困惑.我想将此蚂蚁风格的模式映射到控制器方法:

This is similar to this question, but I am still confused about my situation. I want to map this ant-style pattern to a controller method:

/results/**

也就是说,我希望像www.hostname.com/MyServlet/results/123/abc/456/def/这样的任何URL都可以使用此方法.我有:

That is, I want any URL like www.hostname.com/MyServlet/results/123/abc/456/def/ to go to this method. I have:

<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/results/*</url-pattern>
</servlet-mapping>

和:

@RequestMapping(value="/**", method=RequestMethod.GET)
public ModelAndView handleRequest() {...}

这可以将请求引导到我的方法,但会导致我遇到几个问题:

This works to guide the request to my method, but leads me to several questions:

  1. 如果我添加另一个servlet映射(如<url-pattern>/another-mapping/*</url-pattern>)怎么办???它将也映射到该方法!如何将两者分开?
  2. 为什么网址模式/results/*有效,而/results/**无效?根据蚂蚁路径样式,**意味着包括嵌套的/字符,而*停在下一个/处.因此,它应该仅成功映射URL,例如/results/123,而不是bot /results/123/abc/.对吧?
  1. What if I add another servlet mapping, like <url-pattern>/another-mapping/*</url-pattern>??? It will also get mapped to that method! How can I separate the two?
  2. Why does the url-pattern /results/* work, whereas /results/** doesn't? According to ant path styles, ** means to include nested / characters, whereas * stops at the next /. So, it should only successfully map a URL like /results/123, bot NOT /results/123/abc/. Right?

推荐答案

也许在您的servlet映射中,您希望将所有流量定向到"/*".这样,您可以在控制器中区分对不同的@RequestMapping使用哪种方法.

Perhaps in your servlet mapping you would want to direct all traffic to '/*'. This way, you can distinguish in your controller what method to use with different @RequestMapping's.

<servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

@RequestMapping(value="/results/**", method=RequestMethod.GET)
public ModelAndView handleResults() {...}

@RequestMapping(value="/another-mapping/**", method=RequestMethod.GET)
public ModelAndView handleAnotherMapping() {...}

希望上述内容对数字1有所帮助.就数字2而言,我认为您不能在web.xml域描述符中使用蚂蚁风格"模式匹配器(特别是**).

Hopefully the above will help with number 1. As far as number 2 goes, I do not think that you can use 'ant-style' pattern matchers (specifically **) in your web.xml domain descriptor.

这篇关于使用Spring的@RequestMapping和通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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