刚入门小白,详细请看这篇SpringBoot各种Controller写法_springboot controller-CSDN博客
Spring Boot 提供了@Controller和@RestController两种注解。
返回一个string,其内容就是指向的html文件名称。
-
- @Controller
- public class HelloController {
- @RequestMapping("/hello")
- public String index(ModelMap map) {
- map.addAttribute("name", "ge");
- return "hello";
- }
- }
将返回对象数据转换为JSON格式。
- @RestController
- public class HelloController {
- @RequestMapping("/user")
- public User getUser() {
- User user = new User();
- user.setUsername("ge");
- user.setPassword("kaimen");
- return user;
- }
- }
负责URL路由映射。
如果添加在Controller类上,则该Controller中所有路由映射都会加上该映射规则;
如果添加在方法上,则只对当前方法生效。
属性:value, method, consumes, produces, params, headers 等
- @RequestMapping(value = "/getData", method = RequestMethod.GET)
- public String getData() {
- return "hello";
- }
Method 匹配也可以用 @GetMapping, @PostMapping 等代替。