这里主要讲一下一些常用的注解和用法大概有7个(没提到的并不是不常用的!)。
1. @RequsetMapping
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/hello")
public String hello(){
return "hello,spring-boot";
}
}
作用在建立URL和处理方法之间的对应关系,它可以作用于方法上和类上。
属性:
2. @RequestParam
@RequestMapping("/r8")
public String r8(@RequestParam(value = "name", required = false) String userName){
return "它的name:" + userName;
}
把请求中指定名称的参数给控制器中的形参赋值。
属性:
3. @RequestBody
public String r11(@RequestBody Student student){
return "student 的为" + student;
}
作用:
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 "放回数据";
}
}
6. @CookieValue
@RequestMapping("/getC2")
public String getCookie2(@CookieValue("jincheng") String jincheng){
return "从Cookie中获取:" + jincheng;
}
这里主要是把指定的Cookie名称的值传入控制器方法参数。
属性:
7. @SessionAttribute
@RequestMapping("/getSess3")
public String getSession3(@SessionAttribute("student") String name){
return "它的名字 " + name;
}
这里是Session中寻找一个name为student的Session然后赋值给name。