(資料圖)
Spring MVC框架
Spring MVC框架的優(yōu)點
MVC模式:Spring MVC框架使用MVC模式來組織應(yīng)用程序的代碼,使得應(yīng)用程序的開發(fā)更加模塊化和易于維護。請求處理:Spring MVC框架提供了請求處理的支持,使得應(yīng)用程序可以更加靈活地處理不同類型的請求。視圖技術(shù):Spring MVC框架支持多種視圖技術(shù),包括JSP、Velocity、Freemarker等。Spring MVC框架的示例代碼
以下是一個簡單的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個請求處理方法來處理用戶相關(guān)的操作。這些請求處理方法使用 @RequestMapping
注解來指定它們處理的URL。@RequestParam
注解用于將請求參數(shù)映射到方法參數(shù)。Model
對象用于在請求處理方法和視圖之間傳遞數(shù)據(jù)。
在視圖方面,userList.jsp
和 userDetails.jsp
分別用于顯示用戶列表和用戶詳細(xì)信息。這些JSP頁面使用 JSTL
和 EL
來遍歷用戶列表并顯示用戶信息。其中,
標(biāo)簽用于生成正確的URL以避免硬編碼。
關(guān)鍵詞: