创建实体类User
package com.itbaizhan.ajax.pojo; public class User { private Integer id; private String username; private String password; private Double salary; private String birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public User(Integer id, String username, String password, Double salary, String birthday) { this.id = id; this.username = username; this.password = password; this.salary = salary; this.birthday = birthday; } public User() { } }
创建页面
创建index.jsp中的静态部分
<body> <div> <table align="center" width="60%" border="1"> <tr> <td>ID:</td> <td><input type="text" name="id" id="id"/></td> <td>姓名:</td> <td><input type="text" name="username" id="username"/></td> <td>密码:</td> <td><input type="text" name="password" id="password"/></td> </tr> <tr> <td>收入:</td> <td><input type="text" name="salary" id="salary"/></td> <td>出生日期:</td> <td><input type="text" name="birthday" id="birthday"/></td> <td colspan="2"></td> </tr> <tr align="center"> <td colspan="6"> <input type="button" value="添加用户" id="add" /> <input type="button" value="更新用户" id="update"/> </td> </tr> </table> <hr/> <table align="center" width="60%" bgcolor="" border="1" id="myTable"> <thead> <tr align="center"> <td>ID</td> <td>姓名</td> <td>密码</td> <td>收入</td> <td>生日</td> <td>操作</td> </tr> </thead> <tbody id="tBody"></tbody> </table> </div> </body>
创建UserServlet
@WebServlet("/user.do") public class UserServlet extends HttpServlet { @Override public void init() throws ServletException { } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
配置web.xml
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class> com.itbaizhan.ajax.servlet.UserServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
查询用户列表
页面相关
$(function () { //初始化用户数据 getData(); }); // 获取页面初始化数据 function getData(){ $.getJSON("user.do", {flag:"getData"},function (result) { listUser(result); }); } // 遍历数据生成数据 function listUser(obj){ var str =""; $.each(obj,function(){ str+= "<tr align='center'>" + "<td id='"+this.id+"'>"+this.id +"</td>"+ "<td>"+this.username+"</td>" + "<td>"+this.password+"</td>" + "<td>"+this.salary+"</td>" + "<td>"+this.birthday+"</td>" + "<td><a href='#' onclick='preUpdateUser("+this.id+")'>更新 </a> <a href='#' onclick='deleteUser("+this.id+")'>删除 </a> </td></tr>" }); $("#tBody").prepend(str); }
servlet相关
@Override public void init() throws ServletException { ArrayList<User> list = new ArrayList<>(); User user1 = new User(1,"zhangsan","123",2000d,"1997-09-01"); User user2 = new User(2,"lisi","123",3000d,"1998-08-23"); User user3 = new User(3,"zhaoliu","123",2500d,"1996-05-16"); User user4 = new User(4,"wangwu","123",2080d,"1995-10-12"); User user5 = new User(5,"zhengsan","123",3200d,"1999-12-20"); User user6 = new User(6,"liugang","123",4200d,"1994-04-10"); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); list.add(user6); ServletContext servletContext = this.getServletContext(); servletContext.setAttribute("list",list); } // 获取页面初始化数据 private void getData(HttpServletRequest req, HttpServletResponse resp) throws IOException { List<User> list = (List<User>) this.getServletContext().getAttribute("list"); String s = JSON.toJSONString(list); resp.setContentType("application/json"); PrintWriter pw = resp.getWriter(); pw.print(s); pw.flush(); pw.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("getData".equals(flag)){ this.getData(req,resp); } }
添加用户
页面相关
//添加按钮绑定点击事件 $("#add").click(function(){ addOrUpdateUser("addUser"); }); // 用户添加或者用户更新 function addOrUpdateUser(flag){ // 从页面中获取数据 var userid = $("#id").val(); var username = $("#username").val(); var password = $("#password").val(); var salary = $("#salary").val(); var birthday = $("#birthday").val(); var data = { userid:userid, username:username, password:password, salary:salary, birthday:birthday, flag:flag } $.get("user.do",data,function(result){ alert(result); location.reload(); }); }
servlet相关
/** * 处理添加用户请求 * @param req * @param resp * @throws ServletException * @throws IOException */ private void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException { User user = this.createUser(req); ServletContext servletContext = this.getServletContext(); List<User> list = (List<User>)servletContext.getAttribute("list"); list.add(user); resp.setContentType("text/plain;charset=utf-8"); PrintWriter pw = resp.getWriter(); pw.print("添加成功"); pw.flush(); pw.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("getData".equals(flag)){ this.getData(req,resp); }else if("addUser".equals(flag)){ this.addUser(req,resp); } } // 获取请求数据 private User createUser(HttpServletRequest req){ String userid = req.getParameter("userid"); String username = req.getParameter("username"); String password = req.getParameter("password"); String salary = req.getParameter("salary"); String birthday = req.getParameter("birthday"); User user = new User(); user.setId(Integer.parseInt(userid)); user.setUsername(username); user.setPassword(password); user.setSalary(Double.valueOf(salary)); user.setBirthday(birthday); return user; }
更新用户
页面相关
// 更新之前的数据选择 function preUpdateUser(userid){ var arr = new Array(); $("#"+userid).closest("tr").children().each( function(index,ele){ if(index <=4){ arr[index]= ele.innerText } }); $("#id").val(arr[0]); $("#id").attr("readonly",true); $("#username").val(arr[1]); $("#password").val(arr[2]); $("#salary").val(arr[3]); $("#birthday").val(arr[4]); } //更新按钮绑定点击事件 $("#update").click(function(){ addOrUpdateUser("updateUser"); }); // 用户添加或者用户更新 function addOrUpdateUser(flag){ // 从页面中获取数据 var userid = $("#id").val(); var username = $("#username").val(); var password = $("#password").val(); var salary = $("#salary").val(); var birthday = $("#birthday").val(); var data = { userid:userid, username:username, password:password, salary:salary, birthday:birthday, flag:flag } $.get("user.do",data,function(result){ alert(result); location.reload(); }); }
servlet相关
/** * 处理更新用户请求 * @param req * @param resp * @throws IOException */ private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException{ User user = this.createUser(req); ServletContext servletContext = this.getServletContext(); List<User> userList = (List<User>) servletContext.getAttribute("list"); //list转map Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity())); //根据id获取user User user1 = userMap.get(user.getId()); //删除指定的user userList.remove(user1); //添加新的user userList.add(user); //按id排序 userList.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getId() - o2.getId(); } }); //输出至页面 resp.setContentType("text/plain;charset=utf-8"); PrintWriter pw = resp.getWriter(); pw.print("更新成功"); pw.flush(); pw.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("getData".equals(flag)){ this.getData(req,resp); }else if("addUser".equals(flag)){ this.addUser(req,resp); }else if("updateUser".equals(flag)){ this.updateUser(req,resp); } }
删除用户
页面相关
// 删除用户 function deleteUser(userid){ $("#"+userid).closest("tr").remove(); $.post("user.do", {userid:userid,flag:"delete"},function(result){ alert(result) }) }
servlet相关
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("getData".equals(flag)){ this.getData(req,resp); }else if("addUser".equals(flag)){ this.addUser(req,resp); }else if("updateUser".equals(flag)){ this.updateUser(req,resp); }else if("delete".equals(flag)){ this.deleteUser(req,resp); } } /** * 处理删除用户请求 * @param req * @param resp * @throws ServletException * @throws IOException */ private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ ServletContext servletContext = this.getServletContext(); List<User> userList = (List<User>)servletContext.getAttribute("list"); String userid = req.getParameter("userid"); //list转map Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity())); //根据id获取user if(StringUtils.isNotEmpty(userid)){ User user1 = userMap.get(Integer.parseInt(userid)); //删除指定的user userList.remove(user1); resp.setContentType("text/plain;charset=utf-8"); PrintWriter pw = resp.getWriter(); pw.print("删除成功"); pw.flush(); pw.close(); }else{ resp.setContentType("text/plain;charset=utf-8"); PrintWriter pw = resp.getWriter(); pw.print("删除失败"); pw.flush(); pw.close(); } }
运行效果