@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
属性:
1.value:指定请求的实际地址,指定的地址可以是URI Template 模式;与path用法一样。
2.method: 指定请求的method类型, GET、POST、PUT、DELETE等;
3.produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
4.consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
5.params: 指定request中必须包含某些参数值是,才让该方法处理。
6.headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
package com.fy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(path = "/user")
public class HelloController {
@RequestMapping(path = "/hello")
public String sayHello(){
System.out.println("Hello Spring-mvc");
return "success";
}
@RequestMapping(value = "/sayRequestMapping",method = RequestMethod.POST,produces = "application/json",consumes = "application/json",params = {"uesrname=ddd"},headers = "accept")
public String sayRequestMapping(){
System.out.println("Hello sayRequestMapping");
return "success";
}
}
用法:
1)最基本的,方法级别上应用
@RequestMapping(value="/departments")
public String simplePattern(){
System.out.println("simplePattern method was called");
return "someResult";
}
则访问http://localhost/xxxx/departments的时候,会调用 simplePattern方法了
2) 参数绑定
@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)REST风格的参数
@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)REST风格的参数绑定形式之2
@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中,使用
@PathVariable(“departmentId”) String someDepartmentId,将其绑定为
someDepartmentId,所以这里someDepartmentId为23
5)url中同时绑定多个id
@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)支持正则表达式
@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";
}