Spring MVC Controller控制器
Controller 是 MVC 架构中的控制器层,负责接收请求、调用业务逻辑、返回响应。
@Controller 注解
Java
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public String list(Model model) {
model.addAttribute("users", userService.findAll());
return "user/list";
}
}
@RestController 注解
@RestController = @Controller + @ResponseBody,用于 RESTful API:
Java
@RestController
@RequestMapping("/api/users")
public class UserApiController {
@Autowired
private UserService userService;
@GetMapping
public List<User> list() {
return userService.findAll();
}
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
}
返回值类型
| 返回类型 | 说明 |
|---|---|
| String | 视图名或 redirect:URL |
| ModelAndView | 包含视图名和模型数据 |
| void | 直接操作 response |
| Object | 配合 @ResponseBody 返回 JSON |
| ResponseEntity | 包含状态码和响应体 |
方法参数
| 参数类型 | 说明 |
|---|---|
| HttpServletRequest | 原生请求对象 |
| HttpServletResponse | 原生响应对象 |
| HttpSession | 会话对象 |
| Model | 模型数据容器 |
| @RequestParam | 请求参数 |
| @PathVariable | 路径变量 |
| @RequestBody | 请求体 JSON |
| @RequestHeader | 请求头 |
示例:CRUD 控制器
Java
@Controller
@RequestMapping("/user")
public class UserCrudController {
@Autowired
private UserService userService;
@GetMapping
public String list(Model model) {
model.addAttribute("users", userService.findAll());
return "user/list";
}
@GetMapping("/{id}")
public String detail(@PathVariable Long id, Model model) {
model.addAttribute("user", userService.findById(id));
return "user/detail";
}
@PostMapping
public String save(@ModelAttribute User user) {
userService.save(user);
return "redirect:/user";
}
}
Controller 是单例的,不要使用成员变量存储请求相关的状态。
要点总结
- @Controller 用于页面控制器,@RestController 用于 API 控制器
- 方法参数由 Spring 自动注入
- 返回 String 表示视图名或重定向
- 保持 Controller 轻量,业务逻辑交给 Service
📝 发现内容有误?点击此处直接编辑