springboot(8)RESTful

1、申明RESTful控制器

springboot已经集成了序列化反序列化,并默认使用utf-8编码格式,不会出现中文乱码问题。

1
2
3
4
5
6
@RestController为注解@ResponseBody@Controller的组合
//声明为rest风格的controller,自动对方法的返回值序列化
@RestController
public class TestRestAction {
// TODO
}

2、组合注解

@PostMapping为组合注解@RequestMapping(method=RequestMethod.POST)

@GetMapping为组合注解@RequestMapping(method=RequestMethod.GET)

3、从请求参数中自动获取值

1
2
3
4
5
6
7
8
9
10
11
12
@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地址中获取值

1
2
3
4
@GetMapping("update/{id}")
public String update(@PathVariable(name="id")Integer id) {
return "hello :" +id;
}

5、自动序列化反序列化

1
2
3
4
5
6
7
8
9
@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;
}

对象结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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会将请求参数自动组装成对象。请求参数如图:

这里写图片描述

返回值:

1
2
3
4
5
{
"id": 1,
"username": "wxtx",
"passwd": "123456"
}