一、注解
springboot提供了@Contrller和@RestController。
@Controller:返回页面和数据
@RestController:返回数据
@RestMapping注解:主要做路径映射url
value:请求URL的路径。
method:HTTP请求方法。
@RestMapping(value="user", method= RequestMethod.GET)
1.1 GET
- 无参数
@RequestMapping (value="/hello", method= RequestMethod.GET)
public String hello(String name){
return "123"+name;
}
- 参数传递
@RequestMapping (value="/hello", method= RequestMethod.GET)
public String hello(String name){
return "123"+name;
}
- 参数映射
@RequestParam注解代表参数映射,将传入进来的nickname映射到name
@RequestMapping (value="/hello2", method= RequestMethod.GET)
public String hello2(@RequestParam(value ="nickname",required = false) String name){
return "123"+name;
}
1.2 POST
- 无参数
@RequestMapping(value = "/post1", method = RequestMethod.POST)
public String post1(){
return "hello post";
}
- 带参数
@RequestMapping(value = "/post2", method = RequestMethod.POST)
public String post2(String username, String password){
return username+"-"+password;
}
- Bean封装
@RequestMapping(value = "/post3",method = RequestMethod.POST)
public String post3(User user){
System.out.println(user);
return "post";
}
- json
要在参数前面加一个注解@RequestBody,传入进来的参数名和类的私有变量要保持一致
@RequestMapping(value = "/post34",method = RequestMethod.POST)
public String post4(@RequestBody User user){
System.out.println(user);
return "post";
}
1.3错误
- 404 :路劲不对
- 405:方法不被允许