1、申明RESTful控制器
springboot已经集成了序列化反序列化,并默认使用utf-8编码格式,不会出现中文乱码问题。
@RestController为注解@ResponseBody和@Controller的组合
//声明为rest风格的controller,自动对方法的返回值序列化
@RestController
public class TestRestAction {
// TODO
}
2、组合注解
@PostMapping为组合注解@RequestMapping(method=RequestMethod.POST)
@GetMapping为组合注解@RequestMapping(method=RequestMethod.GET)
3、从请求参数中自动获取值
@PostMapping("login")
public String login(@RequestParam(name="username",required=false)String username,
@RequestParam(name="password",required=false)String password) {
// required=false 表示该值可以为null。默认值为true,表示值为null的时候抛出异常
if(username == null || password == null) {
return "Error";
}
if(username.equals(password)) {
return "hello world";
}
return "Error";
}
4、从URL地址中获取值
@GetMapping("update/{id}")
public String update(@PathVariable(name="id")Integer id) {
return "hello :" +id;
}
5、自动序列化反序列化
@PostMapping("postUser")
public User postUser(User user) {
System.out.println(user);
User u = new User();
u.setId(1);
u.setUsername("wxtx");
u.setPasswd("123456");
return u;
}
对象结构
public class User {
private Integer id;
private String username;
private String passwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", passwd=" + passwd + "]";
}
}
springboot会将请求参数自动组装成对象。请求参数如图:
返回值:
{
“id”: 1,
“username”: “wxtx”,
“passwd”: “123456”
}