Spring MVC之@RequestMapping基本用法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring MVC之@RequestMapping基本用法相关的知识,希望对你有一定的参考价值。

 

1、方法级别上的应用:

1 @RequestMapping(value="/department")
2 
3   public String simpleDapatment(){
4 
5     system.out.println("");
6     return ("result");
7 } 

 

访问 http://localhost/XXXX/department 时,调用simpledepatment方法。

2、参数绑定

@RequestMapping(value="/department")

public String findDepartment(@RequestParaam(departmentId) String departmentId){

System.out.println("asasadas");

return ("someResult");

}

  

访问http://localhost/XXXX/department?departmentId=22 就可以出发findDepartmentf方法。

3、REST 风格的参数

1 @RequestMapping(value="/department/{departmentId}")
2 
3 public String find(@PathVariable String departmentId){
4 
5   system.out.println("asa");
6 
7   return "someRequest";
8 
9 }

 

访问http://localhost/XXXX/department/22 ,@PathVariable 接收REST风格的参数

4、REST 风格的参数2

 1 @RequestMapping(value="/department/{depatmentId}")
 2 
 3 public String findDepartment(@PathVariable(departmentId) String somedepartmentId)
 4 
 5 {
 6 
 7 syso;
 8 
 9 retrrn "sds";
10 
11 }

 

访问http://localhost/XXXX/department/22 ,不同的是,22被传到departmentId,但在实际的方法findDepartment(@PathVariable(departmentId) String someDepartment)中,

将其绑定为someDepartment ,所以someDepartment 是22.

5、 URL绑定多个ID

 1 @RequestMapping(value="/user/{userId}/admin/{adminId}")
 2 
 3 public String findPeople(
 4 
 5   @PathVariable String userId,
 6 
 7   @PathVariable String adminId){
 8 
 9 Syso("userId+adminId");
10 
11 return "sdfs";
12 
13 }

 

6、支持正则表达式

@RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")  
public String regularExpression(  
  @PathVariable String textualPart,  
  @PathVariable String numericPart){  
  
    System.out.println("Textual part: " + textualPart +   
      ", numeric part: " + numericPart);  
    return "someResult";  
}  

 

比如如下的URL:/sometext.123,则输出: 
Textual part: sometext, numeric part: 123. 


以上是关于Spring MVC之@RequestMapping基本用法的主要内容,如果未能解决你的问题,请参考以下文章

一文彻底解密Spring 源码之Spring MVC

Spring之Spring MVC

Spring之Spring MVC

一文彻底解密Spring 源码之Spring MVC

web框架之Spring-MVC环境搭建(转)

Java之Spring mvc详解