1. 简介
Spring MVC框架是MVC设计模式的经典实现,通过基于注解的方式可以使得开发人员更加便捷地完成控制器的编写和请求的处理。本篇攻略整理了常用的Spring MVC注解,目的是为了帮助初学者加速对Spring MVC开发的理解和掌握。
2. 常用注解说明
- @RequestMapping
用于指定请求的URL和请求方式
示例:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String userList(Model model) {
List<User> userList = userService.findAllUsers();
model.addAttribute("users", userList);
return "userList";
}
}
```
- @RequestParam
用于获取请求参数的值
示例:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String searchUser(@RequestParam("name") String name, Model model) {
List<User> userList = userService.searchUser(name);
model.addAttribute("users", userList);
return "userList";
}
}
```
- @ModelAttribute
用于绑定前台表单提交的数据到JavaBean中
示例:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute User user, Model model) {
userService.addUser(user);
model.addAttribute("message", "用户添加成功");
return "success";
}
}
```
- @ResponseBody
用于将控制器中的方法返回值直接放到HTTP响应体中
示例:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable("userId") int userId) {
User user = userService.findUserById(userId);
return user;
}
}
```
- @PathVariable
用于获取URL中的动态变量的值
示例:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable("userId") int userId) {
User user = userService.findUserById(userId);
return user;
}
}
```
- @Validated
用于Bean实体类参数的校验
示例:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Validated User user, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("errors", result.getAllErrors());
return "error";
}
userService.addUser(user);
model.addAttribute("message", "用户添加成功");
return "success";
}
}
```
3. 总结
上述是常用的Spring MVC注解。通过这些注解,开发人员可以在控制器方法中轻松实现URL映射、请求参数获取、响应的返回、动态参数配置、JavaBean绑定、参数校验等功能,大大提高了代码的可读性和可维护性,也更加方便了前后台的交互。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:spring mvc常用注解_动力节点Java学院整理 - Python技术站