使用@RequestMapping匹配URL模式 [英] Matching URL pattern with @RequestMapping
问题描述
这与这个问题非常相似,但我无法不知道如何匹配网址格式.
It's quite similar to this question, but I just couldn't figure out how to match the url pattern.
web.xml:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/activate/*</url-pattern>
</servlet-mapping>
我的控制器:
@RequestMapping(value = {"activate/{key}"}, method = RequestMethod.GET)
public ModelAndView activate(@PathVariable(value = "key") String key) {
...
}
当我尝试访问localhost:9999/myApp/activate/123456789
时,出现以下错误:
When I try to access localhost:9999/myApp/activate/123456789
, I get the following error:
No mapping found for HTTP request with URI [/myApp/activate/123456789] in DispatcherServlet with name 'dispatcher'
我也尝试了<url-pattern>/*</url-pattern>
,发生了同样的事情.
I also tried <url-pattern>/*</url-pattern>
, same thing happens.
但是,通过将<url-pattern>/activate/*</url-pattern>
更改为
<url-pattern>/**</url-pattern>
没有错误出现,但我仍然得到404.
那么,如何映射此网址格式?
However, by changing <url-pattern>/activate/*</url-pattern>
to
<url-pattern>/**</url-pattern>
no error appears, but i still get 404.
So, how do I map this url pattern?
推荐答案
您需要在@RequestMapping
上加上斜杠,例如:
You need to put slash on @RequestMapping
, like:
@RequestMapping(value = {"/activate/{key}"}, method = RequestMethod.GET)
public ModelAndView activate(@PathVariable(value = "key") String key) {
...
}
无论如何,如果您想访问以下上下文:
Anyway, if you wat to get access to following context:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/activate/</url-pattern>
</servlet-mapping>
您不能尝试以下操作:
@RequestMapping(value = {"/{key}"}, method = RequestMethod.GET)
public ModelAndView activate(@PathVariable(value = "key") String key) {
...
}
[已编辑]
就像Leonel所说的那样,您应该使用此配置来使用完整URL(@RequestMapping(value = {"/activate/{key}"}
):
Like Leonel said, you should have this configuration to use with full URL (@RequestMapping(value = {"/activate/{key}"}
):
<url-pattern>/</url-pattern>
这篇关于使用@RequestMapping匹配URL模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!