接着上一讲介绍springMVC针对rest风格的支持。
查询数据 使用前:/user_show?id=120 使用后:/user/120 删除数据 使用前:/user_delete?id=123 使用后:/user/123/delete 更新数据 使用前:/user_updateInput?id=123 使用后:/user/123/update 查询所有数据 使用前:/user_list 使用后:/user/users
以下是查询所有数据的实现。
步骤一:创建user实体;
package zttc.itat.entity; public class Users { private String username; private String password; private String nickname; private String email; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the nickname */ public String getNickname() { return nickname; } /** * @param nickname the nickname to set */ public void setNickname(String nickname) { this.nickname = nickname; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } public Users(String username, String password, String nickname, String email) { super(); this.username = username; this.password = password; this.nickname = nickname; this.email = email; } }
步骤二:新建controller类,在其中新建用于测试的user对象,并通过Model类返回;
package zttc.itat.controller; //此处存在url映射,对应查询所有成员的url为: /user/users @Controller @RequestMapping(value="/user") public class UserController { private Map<String, Users> users = new HashMap<String, Users>(); public UserController() { //新建用于测试的对象 users.put("sdy", new Users("sdy", "123", "宋冬野", "asss")); users.put("ldm", new Users("ldm", "123", "刘东明", "asss")); users.put("zyp", new Users("zyp", "123", "周云蓬", "asss")); users.put("zww", new Users("zww", "123", "张玮玮", "asss")); users.put("wt", new Users("wt", "123", "吴吞", "asss")); } @RequestMapping(value = "/users", method = RequestMethod.GET) public String list(Model model) { //此处返回前台页面的对象为“users”,前台通过${users}来获取对象 model.addAttribute("users", users); //跳转的页面为user文件夹下的list.jsp文件,之前在servlet中有指定前缀和后缀 return "user/list"; } }
步骤三:将放在model中的users在前台进行显示,对应跳转到的url为/user/users。前台使用jstl来循环显示数据,使用前需要导入jstl.jar。在jsp头部导入jstl标签库,对应代码如下所示:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!--头部需要导入jstl标签库,标签以c开头--> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>用户列表</title> </head> <body> <!--在items中获取从controller中得到的users对象。--> <c:forEach items="${users}" var="um" > ${um.value.username } ----${um.value.nickname } ----${um.value.password } ----${um.value.email }<br/> </c:forEach> </body> </html>
对应显示效果如下图所示:
对应工程结构如下图所示:
时间: 2024-10-24 21:27:11