@Controller
public class Example {
/**
* @RequestMapping 注解
* 提供“路由”信息。它告诉Spring,任何带有 / 路径的HTTP请求都应该映射到 home 方法。
* @RestController 注释告诉Spring将结果字符串直接渲染回调用者。
*/
@RequestMapping("/")
public String home() {
return "Hello World!";
}
@GetMapping("/prints")
// @ResponseBody 表明:该方法返回的是数据
public @ResponseBody prints(String name) {
return name;
}
// void:表明该方法无返回值
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
@Controller注解:
表明该类所有的方法返回页面路径,但是在方法上加了@ResponseBody后,该方法返回的是数据。
如果我们还想返回界面可以使用 ModelAndView 方法
@RequestMapping("/")
public ModelAndView index(){
ModelAndView model = new ModelAndView("xxx/xxx"); //界面路径
return model;
}
@PathVariable 获取url中的数据:
如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}", method = RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id){
return "id:" + id;
}
}
如果我们需要在url有多个参数需要获取,实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}", method = RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id, @PathVariable("name") String name){
return "id:" + id + " name:" + name;
}
}
@RequestParam 获取请求参数的值:
@RequestParam 用来处理ContentType: 为 application/x-www-form-urlencoded编码的内容,不管用GET、POST方式提交都行。
如果我们需要获取id参数,地址:localhost:8080/hello?id=1000,实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id){
return "id:" + id;
}
}
地址:localhost:8080/hello?id 如果不输入id的具体值,此时返回的结果为null。
地址:localhost:8080/hello 如果不输入id参数,则会报错。
@RequestParam 注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello", method = RequestMethod.GET)
//required=false 表示url中可以不穿入id参数,此时就使用默认参数
public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "1") Integer id){
return "id:" + id;
}
}
@RequestBody注解:
该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
@RequestBody 接收的是一个Json对象的字符串,而不是一个Json对象。在ajax请求往往传的都是Json对象,用 JSON.stringify(data)的方式就能将对象变成字符串。
@GetMapping、@PostMapping 组合注解:
@GetMapping = @RequestMapping(method = RequestMethod.GET)的缩写,是一个组合注解
@PostMapping = @RequestMapping(method = RequestMethod.POST)的缩写,是一个组合注解
Spring4.3 中引进了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping},来帮助简化常用的HTTP方法的映射,并更好地表达被注解方法的语义。
注意:
1.接收时间的参数前面要加上@DateTimeFormat(pattern=”“)注解
2.同时对于LocalDateTime类型,注解里面的时分秒不能省略,前端也必须传进来,传的时候必须是双位数!如果没有,就要用00:00:00表示
3.LocalDate 类型的注解也可以加上时分秒,但是年月日后面的不会被接收和显示。
@ApiModelProperty(value = "创建时间", example = "2019-10-18")
@DataTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime create_time;