最近从Struts转投SpringMVC,看代码时发现这个注解,感觉其作用应该和Struts的action差不多,把用法记录下来。
1.
代码语言:javascript复制@RequestMapping(value="/departments")
public String simplePattern(){
System.out.println("simplePattern method was called");
return "someResult";
}
//访问http://localhost/xxxx/departments的时候,会调用implePattern方法了
2.
代码语言:javascript复制@RequestMapping(value="/departments")
public String findDepatment(
@RequestParam("departmentId") String departmentId){
System.out.println("Find department with ID: " departmentId);
return "someResult";
}
//形如这样的访问形式: /departments?departmentId=23就可以触发访问findDepatment方法了
3.
代码语言:javascript复制@RequestMapping(value="/departments/{departmentId}")
public String findDepatment(@PathVariable String departmentId){
System.out.println("Find department with ID: " departmentId);
return "someResult";
}
// 形如REST风格的地址访问,比如 /departments/23,其中用(@PathVariable接收rest风格的参数
4.
代码语言:javascript复制@RequestMapping(value="/departments/{departmentId}")
public String findDepatmentAlternative(
@PathVariable("departmentId") String someDepartmentId){
System.out.println("Find department with ID: " someDepartmentId);
return "someResult";
}
// 这个有点不同,就是接收形如/departments/23的URL访问,把23作为传入的departmetnId,,但是在实际的方法findDepatmentAlternative中,使用
5.
代码语言:javascript复制@RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")
public String findEmployee(
@PathVariable String departmentId,
@PathVariable String employeeId){
System.out.println("Find employee with ID: " employeeId
" from department: " departmentId);
return "someResult";
}
//绑定多个参数
6.
代码语言:javascript复制@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.