(资料图片仅供参考)
以下是一个简单的Spring MVC框架示例代码:
UserController.java
@Controller@RequestMapping("/user")public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/addUser", method = RequestMethod.POST) public String addUser(User user) { userService.addUser(user); return "redirect:/user/list"; } @RequestMapping(value = "/updateUser", method = RequestMethod.POST) public String updateUser(User user) { userService.updateUser(user); return "redirect:/user/list"; } @RequestMapping(value = "/deleteUser", method = RequestMethod.GET) public String deleteUser(@RequestParam("userId") int userId) { userService.deleteUser(userId); return "redirect:/user/list"; } @RequestMapping(value = "/getUser", method = RequestMethod.GET) public String getUser(@RequestParam("userId") int userId, Model model) { User user = userService.getUser(userId); model.addAttribute("user", user); return "userDetails"; } @RequestMapping(value = "/list", method = RequestMethod.GET) public String listUsers(Model model) { List userList = userService.getAllUsers(); model.addAttribute("userList", userList); return "userList"; }}
userList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> User List User List
User ID User Name Action ${user.userId} ${user.userName} ?userId=${user.userId}">View | ?userId=${user.userId}">Delete
">Add User
userDetails.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> User Details User Details
User ID ${user.userId} User Name ${user.userName}
">Back to User List
在这个示例中,UserController.java
定义了5个请求处理方法来处理用户相关的操作。这些请求处理方法使用 @RequestMapping
注解来指定它们处理的URL。@RequestParam
注解用于将请求参数映射到方法参数。Model
对象用于在请求处理方法和视图之间传递数据。
在视图方面,userList.jsp
和 userDetails.jsp
分别用于显示用户列表和用户详细信息。这些JSP页面使用 JSTL
和 EL
来遍历用户列表并显示用户信息。其中,
标签用于生成正确的URL以避免硬编码。
Copyright @ 2015-2022 海外生活网版权所有 备案号: 沪ICP备2020036824号-21 联系邮箱:562 66 29@qq.com