这里主要讲一下一些常用的注解和用法大概有7个(没提到的并不是不常用的!)。
1. @RequsetMapping
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/hello")
public String hello(){
return "hello,spring-boot";
}
}
作用在建立URL和处理方法之间的对应关系,它可以作用于方法上和类上。
1. 作用在类上:第一级的访问目录。
2. 作用于在方法上:第二级的访问目录上。
属性:
1. name:方法的注释。
2. value :指定请求的实际地址。
3. path:与value同义。
4. method:指定请求的method类型(GET,POST,PUT等等)。
5. params:请求中必须包含params属性的规定的参数时,才能执行该请求。
6. headers:请求中不行包含某些指定的header值,才能够请求。
7. consumes:指定请求的提交内容类型。
8.produces:请求放回内容的类型。
2. @RequestParam
@RequestMapping("/r8")
public String r8(@RequestParam(value = "name", required = false) String userName){
return "它的name:" + userName;
}
把请求中指定名称的参数给控制器中的形参赋值。
属性:
1. value:请求参数中的名称。
2.required:把请求中是否必须提供参数。(默认值为true,表示必须提供,如果不提供就会报错)。
3. defaultValue:默认值。
3. @RequestBody
public String r11(@RequestBody Student student){
return "student 的为" + student;
}
作用:
1. 用于获取请求体内容。
2. 把获得的json类型的数据转成pojo对象。
4. @PathVariable
@RequestMapping("/r13/{name}/{id}")
public String r13(@PathVariable("name") String name, @PathVariable("id") Integer id){
return "它的name" + name + "它的id" + id;
}
它的作用是在请求url中去获取{xxxx}参数,简单来说就是从路径中获取参数。
5. @ResponseBody + @Controller
简单来说可以理解为:@ResponseBody + @Controller == @RestController。运用的场所不同使用的地方也不同。
@Controller
@RequestMapping("/res")
public class ResponseController {
@RequestMapping("haha")
public String haha(){
return "/hahah.html";
}
@ResponseBody
@RequestMapping("/date")
public String data(){
return "放回数据";
}
}
在整个类中是用@Controller注解时,放回的类型需要是HTML标签页面,如果是其他类型就会报错,所以我们在这里应用了另一个新的注解@ResponseBody,放回数据不是HTML标签的页面,而是其他类型的数据。
6. @CookieValue
@RequestMapping("/getC2")
public String getCookie2(@CookieValue("jincheng") String jincheng){
return "从Cookie中获取:" + jincheng;
}
这里主要是把指定的Cookie名称的值传入控制器方法参数。
属性:
1. value:指定cookie的名称。
2. required:是否必须有此cookie。
7. @SessionAttribute
@RequestMapping("/getSess3")
public String getSession3(@SessionAttribute("student") String name){
return "它的名字 " + name;
}
这里是Session中寻找一个name为student的Session然后赋值给name。