关于SpringMVC的小demo可以参考这里! url-pattern如果看过前一篇入门的帖子,应该了解到spring mvc在启动前必须要在web.xml中配置servlet,这样才能拦截到想要映射的url地址。 <servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping> 其中servlet配置了
RequestMapping()基于注解风格的Spring MVC就是通过这个方法来定义映射的url的,常使用的方式如下: 基于普通的url这种是最简单的url映射,可以接收到 @RequestMapping('/hello')
public @ResponseBody String test() {
return 'hello!';
} 基于多个普通的url路径RequestMapping可以同时指定多个url,映射到同一个应答逻辑中: //普通的url路径映射
@RequestMapping(value={'/multi1','/multi2','/test/multi'})
public @ResponseBody String multiUrl() {
return 'test multi url';
} 基于路径变量的URL映射这种URL映射可以直接在路径上指定变量,通过 //基本的URL模板映射
@RequestMapping(value='/user1/{name}')
public @ResponseBody String basicUrl1(@PathVariable String name){
return 'hello' name;
}
@RequestMapping(value='/user2/{name}/test')
public @ResponseBody String basicUrl2(@PathVariable String name){
return 'hello' name 'test';
}
@RequestMapping(value='/user1/{name}/test/{age}')
public @ResponseBody String basicUrl3(@PathVariable String name,@PathVariable int age){
return 'hello' name ' age' age;
} 基于通配风格的url映射第一种: @RequestMapping(value='/ant1?')
public @ResponseBody String ant1(){
return 'ant1?';
}
localhost:8080/context/ant12 或者
localhost:8080/context/ant1a 第二种: @RequestMapping(value='/ant2*')
public @ResponseBody String ant2(){
return 'ant2*';
}
localhost:8080/context/ant2aaaa 或者
localhost:8080/context/ant2 第三种:@RequestMapping(value='/ant3/*')
public @ResponseBody String ant3(){
return 'ant3/*';
}
localhost:8080/context/ant3/aaaa 或者
localhost:8080/context/ant3/123 第四种: @RequestMapping(value='/ant4/**')
public @ResponseBody String ant4(){
return 'ant4/**';
}
localhost:8080/context/ant4/ 或者
localhost:8080/context/ant4/aaa 或者
localhost:8080/context/ant4/aaa/123 混用统配和路径变量 //混用
@RequestMapping(value='/ant5/**/{name}')
public @ResponseBody String ant5(@PathVariable String name){
return 'ant url ' name;
} 它能匹配 localhost:8080/context/ant5/123 或者
localhost:8080/context/ant5/aaa/123 或者
localhost:8080/context/ant5/aaa/123/test 最后一个会被当做name值 基于正则的url映射这个比较有意思,它支持{名称:正则表达式}的写法,以另一种风格限制url的映射。 //正则表达式
@RequestMapping(value='/student/{name:\\w }-{age:\\d }')
public @ResponseBody String regUrl(@PathVariable String name,@PathVariable int age){
return 'name:' name ' age:' age;
} 例如上面的URL就只能匹配如: localhost:8080/context/student/wangwu-33 或者
localhost:8080/context/student/zhao4-22 参考1 开勇学Spring mvc —— 不得不说,这个讲的很全 |
|