注解
-
@RequestMapping:(作用于类或者方法)
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址 作为父路径。
RequestMapping注解有六个属性,下面我们把它分成三类进行说明。- value(默认属性),path:请求地址
- name:此处name属性,相当于方法的注释,使方法更易理解
@RequestMapping(value = "/hello",name = "Hello World!") @ResponseBody public String hello(){ return "hello"; }
- method:该属性用来表示该方法处理哪些HTTP请求方式
属性值 - RequestMethod.GET
- RequestMethod.HEAD
- RequestMethod.POST
- RequestMethod.PUT
- RequestMethod.PATCH
- RequestMethod.DELETE
- RequestMethod.OPTIONS
- RequestMethod.TRACE
- params:该属性指定,请求中必须包含params属性规定的参数时,才能执行该请求,否则会发生400错误
/*必须要传参数name*/ @RequestMapping(path = "/hello",params = {"name"}) public String hello(String name) { System.out.println("传的值是:" + name); return "index"; }
- header:请求头中必须包含规定的键值对
/*Headers中必须要有Referer=http://localhost/SSM/index.jsp,否则会发生404*/ @RequestMapping(path = "/hello",headers = {"Referer=http://localhost/SSM/index.jsp"}) public String hello(String name) { System.out.println("传的值是:" + name); return "index"; }
- consumers:指定处理请求的提交内容类型(Content-Type),例如:application/json、text/html时,才能够让该方法处理请求
/*Content-Type的值必须是text/html,否则会发生415-不支持的媒体类型错误*/ @RequestMapping(path = "/hello",consumes = {"text/html"}) public String hello(String name) { System.out.println("传的值是:" + name); return "index"; }
- produces:指定返回的内容类型,返回的内容类型必须是request请求头(Accept)中所包含的类型 不常用,这里不介绍
-
@GetMapping
@RequestMapping
@DeleteMapping
@PatchMapping
@PostMapping
@PutMapping :与上面的注解中method属性值功能相同,表示响应相应的请求 -
@RequestParam:(作用于方法参数)
用于将请求URL中的模板变量映射到功能处理方法的参数上。
属性:- name,value:地址上的参数名
- required:默认true,代表必须传参数,不然会发生400错误
注意:前端必须要传的参数,最好使用该注解,不是必须的参数可以不用,但是方法中参数前端没有传的话会变成java中的默认值
-
@PathVariable:(作用于方法参数)
用于将请求URL(Rest风格)中的模板变量映射到功能处理方法的参数上。
属性:- name,value: 地址上的参数名
- required: 默认true,代表必须要传参数才能访问到
- 访问路径参数不可省略的情况下:
- 访问路径参数可以省略的情况下:
-
@RequestAttribute:(作用于方法参数)
属性:
- name,value:查找request域中的key
扩展:可以用Moldel对象往request请求域中存数据 - required:默认为true,代表request域中必须要有key,否则报400错误
- name,value:查找request域中的key
-
@ResponseBody:(作用于类或者方法)
使用该注解后,方法的return的字符串将不会将不会被视图解析器拼接成新的访问地址,而被写入 到Response对象的body数据区(一般用于响应前端请求的json数据)
-
@RequestHeader:(作用于方法参数)
使用该注解后,会把请求头中value的值赋给方法参数
属性- value,name:要获取请求头的键
- required:默认为true,代表请求头中必须有键名为value,否则会报400错误
-
@CookieValue:(作用域方法参数)
使用该注解后,会从请求域中把value的值赋给方法参数