spring的RequestMapping注解
@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
RequestMapping可以用于类和方法上,用于类上表示所有响应请求的方法都是以地址作为父路径如下
访问地址必须以 /user/RequestMpping来访问
@Controller
@RequestMapping(path = ("user"))
public class HelloController {
//访问地址可以填多个如:RequestMapping和hello
@RequestMapping( value = {"/RequestMpping","/hello"},params = {"name=zhangsan"},headers ="Accept")//必须传值名字为name 如果name=zhangsan
public String RequestMpping(){
System.out.println("RequestMapping");
return "success";
}
}
RequestMapping有以下这几个属性:
- values:请求的实际地址
- method: 指定请求的method类型, GET、POST、PUT、DELETE;所有的请求默认都会是 HTTP GET 类型的。
- path:和values用法相同,相当于values。
- params:使用requset方式传值或访问时,提交时必须带有该类型。如:params = {“name=zhangsan”},必须要有/RequestMpping?name=zhangsan
- headers: 根据请求中的消息头内容缩小,请求映射,的范围。如 “Accept”,“content-type=text/plain” ,“content-type=text/html”
- produces:指定返回值类型,不但可以返回值的类型还可以设置返回值的字符编码
- consumes:指定处理请求的提交内容(Content-Type),如:application/json, text/html;
带有@RequestParam的RequestMapping
可以把传过来的参数和方法参数绑定在一起代码如下
@RequestMapping( value = {"/RequestMpping","/hello"})
public String RequestMpping(@RequestParam("name") String name){
System.out.println("RequestMapping");
return "success";
}
//如果请求参数和处理方法参数的名称一样的话,@RequestParam 注解的 value 这个参数就可省掉了
@RequestMapping( value = {"/RequestMpping","/hello"},method = {RequestMethod.GET})
public String RequestMpping(@RequestParam(required = false//定义该值不是必须要传的值,
defaultValue = "zhangsan"//当没有值传入时自定义一个值)
String name){
System.out.println(name);
return "success";
}
RequestMapping的快捷方式
Spring 4.3 引入了 @RequestMapping 的组合注解。组合注解可以更好的表达被注解方法的语义。它们所扮演的角色就是针对 @RequestMapping 的封装。
例如,@GetMapping 相当于@RequestMapping(method =RequestMethod.GET) 的一个快捷方式。
方法级别的注解变体有如下几个:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
本文有部分是从网上收集而来,如果有侵权请联系删除