学了spring boot感觉 ,和springMVC在许多地方还是时分相似的,,请求处理都是使用@RequestMapping注解,但是启动方式上有很大不同,,
springMVC是web项目,需要通过tomcat进行启动
springBoot则类似应用程序,使用main进行启动(SpringApplication.run()),哈哈这是表象,看了这个日志,才知道,springboot也是通过tomcat启动的(Tomcat started on port(s): 8080 (http))
一。不带参请求
// @RequestMapping(value = {"/hello","/hi"} ,method = RequestMethod.GET)
@PostMapping("/hello")
public String sayHello(){
return "hello Spring boot";
}
@RequestMapping(value = “/hello” ,method = RequestMethod.GET)
和
@GetMapping(“/hello”)
两个注解的作用是相同的,,当然,Get换成 post/put等也可以
{“/hello”,”/hi”},,或的关系,请求任意一个即可映射到sayHello()中
二。接收请求参数
自从有了spring booti,,接收参数将变得十分简单
@GetMapping("/hello/{id}")
public String sayHello(@PathVariable int id, @RequestParam(value = "name", required = false, defaultValue = "xiaobai") String name) {
return " id:" + id + " name:" + name;
// return "name:"+ name;
}
(1)可以在映射字符串后添加“ {id} ”,接收与请求链接对应的参数,,@PathVariable(“name”)注解可携带映射名称({}花括号中的字符串和变量名不同时,相同时不需要)
(2)@RequestParam(value = “name”)注解,可以解析URL链接中的GET请求(如baidu.com?name=baidu。,,,可以解析后面字符串“百度”)
(3)@RequestParam(value = “name”, required = false, defaultValue = “xiaobai”)
required指是否必须传入,。。defaultValue,,设置默认值
三。接收请求参数并封装为对象
@PostMapping("/hello2")
public String sayHello(Student student) {
return " id:" + student.getId() + " name:" + student.getName();
}
sayHello(Student student),将此方法中的参数直接换成对象,即可接收post表单中传入的信息,,,,就这么简单粗暴
四。接受信息限制
(1)首先需要在实体类中,添加注解 @Min,当然@Max也有
@Min(value = 10, message = "小于10,,不可以的")
private int id;
(2)在需要验证的参数中加入 @Valid 注解
通过 result.getFieldError().getDefaultMessage();可以获取,注解中的message
@PostMapping("/hello2")
public String sayHello(@Valid User student, BindingResult result) {
if (result.hasErrors()) {
System.out.println("错了");
return result.getFieldError().getDefaultMessage();
}
return " id:" + student.getId() + " name:" + student.getName();
}