SpringBoot的MVC支持主要涉及实际项目中最常用的几个注解:@RestController,@RequestMapping,@PathVariable,@RequestParam,@RequestBody.
一.@RestController
@RestController包含了原来的@Controller和@ResponseBody注解,作用是将controller层返回的数据以json形式传给前端。
但如果是用模板类似与thymeleaf渲染不是前后端分离的这种情况就不能使用@RestController,而是使用@Controller。
二.@RequestMapping
@RequestMapping 是一个用来处理请求地址映射的注解,它可以用于类上,也可以用于方法上。在类的级别上的注解会将一个特定请求映射到一个控制器之上,表示类中的所有响应请求的方法都是以该地址作为父路径.
在方法的级别表示进一步指定到处理方法的映射关系。
该注解常用的三个属性:value、method 和 produces。
value 属性:指定请求的实际地址, value 可以省略不写
method 属性:指定请求的类型,主要有 GET 、 PUT 、 POST 、 DELETE ,默认为 GET
produces 属性:指定返回内容类型,如 produces = "application/json; charset=UTF-8"
举例:
@RestController
@RequestMapping(value = "/test", produces = "application/json; charset=UTF-8")
public class TestController {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String testGet() {
return "success";
}
}
对应不同的请求类型,也可以用@GetMapping,@PutMapping,@PostMapping和@DeleteMapping等注解。
三.@PathVariable
@PathVariable主要用来获取请求过来的url参数.
例子1:一个 GET 请求携带一个参数 id 过来,我们将 id 作为参数接收。
@GetMapping("/user/{id}")
public String testPathVariable(@PathVariable Integer id) {
System.out.println("获取到的id为:" + id);
return "success";
}
例子2:url 中的参数和方法接收参数不一致
@RequestMapping("/user/{idd}")
public String testPathVariable(@PathVariable(value = "idd") Integer id) {
System.out.println("获取到的id为:" + id);
return "success";
}
例子3:对于访问的url:localhost:8080/test/user/2/felix占位符的位置不在最后也可以获取
@GetMapping("/user/{idd}/{name}")
public String testPathVariable(@PathVariable(value = "idd") Integer id, @PathVariable String name)
{
System.out.println("获取到的id为:" + id);
System.out.println("获取到的name为:" + name);
return "success";
}
四.@RequestParam
@RequestParam是从 request 里面获取参数值,对于get请求接收用?拼接在url中的参数
例子1:请求url为http://localhost:8080/user?id=1
@GetMapping("/user")
public String testRequestParam(@RequestParam Integer id)
{
System.out.println("获取到的id为:" + id);
return "success";
}
例子2:请求url中的参数和方法参数不一致,http://localhost:8080/user?idd=1
对于post请求
@RequestMapping("/user")
public String testRequestParam(@RequestParam(value = "idd", required = false) Integer id)
{
System.out.println("获取到的id为:" + id);
return "success";
}
除了valve属性还有2个常用属性:
required 属性:true 表示该参数必须要传,否则就会报 404 错误,false 表示可有可无。
defaultValue 属性:默认值,表示如果请求中没有同名参数时的默认值。
例子3:注解用于post请求时,用于接收前端表单提交的参数,用法和前面一样
@PostMapping("/form1")
public String testForm(@RequestParam String username, @RequestParam String password) {
System.out.println("获取到的username为:" + username);
System.out.println("获取到的password为:" + password);
return "success";
}
例子4:如果表单数据很多,我们不可能每个参数逐个地添加@RequestParam注解。我们可以封装一个实体类来接收参数,实体类中的属性名和表单中的参数名一致即可。
public class User {
private String username;
private String password;
// setter getter
}
使用实体接收不用添加@RequestParam,框架会自动转换
@PostMapping("/form2")
public String testForm(User user)
{
System.out.println("获取到的username为:" + user.getUsername());
System.out.println("获取到的password为:" + user.getPassword());
return "success";
}
实际项目中,一般都是封装一个实体类来接收表单数据,因为实际项目中表单数据一般都很多。