接口声明
@RestController
//表示该类为请求处理类
public class HttpDeal {
@RequestMapping("/login")
//这个方法处理哪一个地址过来的请求
public String hello()
{
return "返回给浏览器";
}
}
接收参数
@RequestMapping("/login")
public String login(int id,String password){
return "登录成功"+id;
}
传递参数与接收参数不一致 必传参数
使用@RequestParam进行映射,前端只需要给name传递值即可 name=id,设置了@RequestParam参数必须传递否则报错,
@RequestMapping("/login")
public String login(@RequestParam(name="name") int id, String password){
return "登录成功"+id;
}
设置非必传参数
@RequestParam(required = false)
//required 表示参数非必传
接收时间参数
pattern 表示传递的格式
@RequestMapping("/update")
public String login(@DateTimeFormat(pattern = "HH:mm") LocalTime time){
System.out.println(time);
return "OK";
}
JSON类型参数
{
"user":"123",
"password":"456"
}
public class User {
private String user;
private String password;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"user='" + user + '\'' +
", password='" + password + '\'' +
'}';
}
}
@RequestMapping("/update")
public String login(@RequestBody User user){
System.out.println(user.getPassword());
return "OK";
}
数组参数接收
前端
http://127.0.0.1:8080/login?id=488&id=123&id=45
@RequestMapping("/login")
public String login(String[] id){
//id参数名需相同
return Arrays.toString(id);
}
列表参数接收
使用列表接收需要添加RequestParam 注解
http://127.0.0.1:8080/login?id=488&id=123&id=45
@RequestMapping("/login")
public String login(@RequestParam List<String> id){
System.out.println(id);
return "OK";
}