码迷,mamicode.com
首页 > Web开发 > 详细

JSP+Servlet+Ajax实现用户增删改查的例子

时间:2019-05-03 13:02:02      阅读:1707      评论:0      收藏:0      [点我收藏+]

标签:text   java   head   manager   users   resultset   dia   mic   dal   

一、数据库设计

【用户表User】

技术图片

已有的测试数据

技术图片

 

二、Java代码编写

Java EE的架构一般分为以下五层:

①.Domain

②.DAO

③.Service

④.Controller

⑤.View

这里的项目结构如下:

技术图片

 

1.Domain层

User.java

 1 package domain;
 2 
 3 import java.util.Date;
 4 
 5 public class User {
 6     
 7     public User() {
 8         
 9     }
10     
11     private Integer id;
12     
13     private String account;
14     
15     private String password;
16     
17     private String name;
18     
19     private String info;
20     
21     private Date createTime;
22     
23     private Date modifiedTime;
24 
25     public Integer getId() {
26         return id;
27     }
28 
29     public void setId(Integer id) {
30         this.id = id;
31     }
32 
33     public String getAccount() {
34         return account;
35     }
36 
37     public void setAccount(String account) {
38         this.account = account;
39     }
40 
41     public String getPassword() {
42         return password;
43     }
44 
45     public void setPassword(String password) {
46         this.password = password;
47     }
48 
49     public String getName() {
50         return name;
51     }
52 
53     public void setName(String name) {
54         this.name = name;
55     }
56 
57     public String getInfo() {
58         return info;
59     }
60 
61     public void setInfo(String info) {
62         this.info = info;
63     }
64 
65     public Date getCreateTime() {
66         return createTime;
67     }
68 
69     public void setCreateTime(Date createTime) {
70         this.createTime = createTime;
71     }
72 
73     public Date getModifiedTime() {
74         return modifiedTime;
75     }
76 
77     public void setModifiedTime(Date modifiedTime) {
78         this.modifiedTime = modifiedTime;
79     }
80 
81     @Override
82     public String toString() {
83         return "User [id=" + id + ", account=" + account + ", password=" + password + ", name=" + name + ", info="
84                 + info + ", createTime=" + createTime + ", modifiedTime=" + modifiedTime + "]";
85     }
86     
87 }

 

 2.Dao层

UserDao.java

 1 package dao;
 2 
 3 import java.util.List;
 4 
 5 import domain.User;
 6 
 7 public interface UserDao {
 8     
 9     /** 显示所有用户 */
10     public List<User> listAll();
11     
12     /** 添加一个用户 */
13     public boolean add(User user);
14     
15     /** 根据id删除一个用户 */
16     public boolean deleteById(Integer id);
17     
18     /** 更新一个用户 */
19     public boolean update(User user);
20     
21     /** 根据id查找一个用户 */
22     public User getById(Integer id);
23     
24 }

 

UserDaoImpl.java

  1 package dao.impl;
  2 
  3 import java.sql.Connection;
  4 import java.sql.PreparedStatement;
  5 import java.sql.ResultSet;
  6 import java.sql.SQLException;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 
 10 import dao.UserDao;
 11 import domain.User;
 12 import util.DBUtil;
 13 
 14 public class UserDaoImpl implements UserDao {
 15 
 16     @Override
 17     public List<User> listAll() {
 18         List<User> users = new ArrayList<User>();
 19         Connection conn = DBUtil.getConnection();
 20         String sql = "select * from user";
 21         try {
 22             PreparedStatement pst = conn.prepareStatement(sql);
 23             ResultSet rst = pst.executeQuery();
 24             while (rst.next()) {
 25                 User user = new User();
 26                 user.setId(rst.getInt("id"));
 27                 user.setAccount(rst.getString("account"));
 28                 user.setPassword(rst.getString("password"));
 29                 user.setName(rst.getString("name"));
 30                 user.setInfo(rst.getString("info"));
 31                 user.setCreateTime(rst.getTimestamp("gmt_create"));
 32                 user.setModifiedTime(rst.getTimestamp("gmt_modified"));
 33                 users.add(user);
 34             }
 35             rst.close();
 36             pst.close();
 37         } catch (SQLException e) {
 38             e.printStackTrace();
 39         }
 40         return users;
 41     }
 42 
 43     @Override
 44     public boolean add(User user) {
 45         Connection conn = DBUtil.getConnection();
 46         String sql = "insert into user(account, password, name, info) value (?, ?, ?, ?)";
 47         try {
 48             PreparedStatement pst = conn.prepareStatement(sql);
 49             pst.setString(1, user.getAccount());
 50             pst.setString(2, user.getPassword());
 51             pst.setString(3, user.getName());
 52             pst.setString(4, user.getInfo());
 53             int count = pst.executeUpdate();
 54             pst.close();
 55             return count > 0 ? true : false;
 56         } catch (SQLException e) {
 57             e.printStackTrace();
 58         }
 59         return false;
 60     }
 61 
 62     @Override
 63     public boolean deleteById(Integer id) {
 64         Connection conn = DBUtil.getConnection();
 65         String sql = "delete from user where id = ?";
 66         try {
 67             PreparedStatement pst = conn.prepareStatement(sql);
 68             pst.setInt(1, id);
 69             int count = pst.executeUpdate();
 70             pst.close();
 71             return count > 0 ? true : false;
 72         } catch (SQLException e) {
 73             e.printStackTrace();
 74         }
 75         return false;
 76     }
 77 
 78     @Override
 79     public boolean update(User user) {
 80         Connection conn = DBUtil.getConnection();
 81         String sql = "update user set account = ?, password = ?, name = ?, info = ? where id = ?";
 82         try {
 83             PreparedStatement pst = conn.prepareStatement(sql);
 84             pst.setString(1, user.getAccount());
 85             pst.setString(2, user.getPassword());
 86             pst.setString(3, user.getName());
 87             pst.setString(4, user.getInfo());
 88             pst.setInt(5, user.getId());
 89             int count = pst.executeUpdate();
 90             pst.close();
 91             return count > 0 ? true : false;
 92         } catch (SQLException e) {
 93             e.printStackTrace();
 94         }
 95         return false;
 96     }
 97 
 98     @Override
 99     public User getById(Integer id) {
100         User user = new User();
101         Connection conn = DBUtil.getConnection();
102         String sql = "select * from user where id = ?";
103         try {
104             PreparedStatement pst = conn.prepareStatement(sql);
105             pst.setInt(1, id);;
106             ResultSet rst = pst.executeQuery();
107             while (rst.next()) {
108                 user.setId(rst.getInt("id"));
109                 user.setAccount(rst.getString("account"));
110                 user.setPassword(rst.getString("password"));
111                 user.setName(rst.getString("name"));
112                 user.setInfo(rst.getString("info"));
113                 user.setCreateTime(rst.getTimestamp("gmt_create"));
114                 user.setModifiedTime(rst.getTimestamp("gmt_modified"));
115             }
116             rst.close();
117             pst.close();
118         } catch (SQLException e) {
119             e.printStackTrace();
120         }
121         return user;
122     }
123 
124 }

 

3.Service层

UserService.java

 1 package service;
 2 
 3 import java.util.List;
 4 
 5 import domain.User;
 6 
 7 public interface UserService {
 8     
 9     /** 显示所有用户 */
10     public List<User> listAll();
11     
12     /** 添加一个用户 */
13     public boolean add(User user);
14     
15     /** 根据id删除一个用户 */
16     public boolean deleteById(Integer id);
17     
18     /** 更新一个用户 */
19     public boolean update(User user);
20     
21     /** 根据id查找一个用户 */
22     public User getById(Integer id);
23     
24 }

 

UserServiceImpl.java

 1 package service.impl;
 2 
 3 import java.util.List;
 4 
 5 import dao.UserDao;
 6 import dao.impl.UserDaoImpl;
 7 import domain.User;
 8 import service.UserService;
 9 
10 public class UserServiceImpl implements UserService {
11 
12     @Override
13     public List<User> listAll() {
14         UserDao userDao = new UserDaoImpl();
15         return userDao.listAll();
16     }
17 
18     @Override
19     public boolean add(User user) {
20         UserDao userDao = new UserDaoImpl();
21         return userDao.add(user);
22     }
23 
24     @Override
25     public boolean deleteById(Integer id) {
26         UserDao userDao = new UserDaoImpl();
27         return userDao.deleteById(id);
28     }
29 
30     @Override
31     public boolean update(User user) {
32         UserDao userDao = new UserDaoImpl();
33         return userDao.update(user);
34     }
35 
36     @Override
37     public User getById(Integer id) {
38         UserDao userDao = new UserDaoImpl();
39         return userDao.getById(id);
40     }
41 
42 }

 

4.Controller层

  1 package controller;
  2 
  3 import java.io.IOException;
  4 import java.util.List;
  5 
  6 import javax.servlet.ServletException;
  7 import javax.servlet.annotation.WebServlet;
  8 import javax.servlet.http.HttpServlet;
  9 import javax.servlet.http.HttpServletRequest;
 10 import javax.servlet.http.HttpServletResponse;
 11 
 12 import domain.User;
 13 import net.sf.json.JSONArray;
 14 import net.sf.json.JSONObject;
 15 import service.UserService;
 16 import service.impl.UserServiceImpl;
 17 import util.JSONUtil;
 18 
 19 @WebServlet("/UserServlet")
 20 public class UserServlet extends HttpServlet {
 21     
 22     private static final long serialVersionUID = 1L;
 23        
 24     public UserServlet() {
 25         super();
 26     }
 27     
 28     protected void doGet(HttpServletRequest request, HttpServletResponse response)
 29             throws ServletException, IOException {
 30         // 设置返回编码格式,解决中文乱码
 31         response.setCharacterEncoding("utf-8");
 32         
 33         // 根据action的值来执行不同的动作,例如显示所有用户或显示单个用户
 34         String action = request.getParameter("action");
 35         
 36         // 显示所有用户
 37         if (action.equals("listAll")) {
 38             UserService userService = new UserServiceImpl();
 39             List<User> users = userService.listAll();
 40             
 41             // 返回JSON数据格式
 42             JSONArray jsonArr = JSONArray.fromObject(users);
 43             JSONObject jsonObjOut = new JSONObject();
 44             jsonObjOut.put("users", jsonArr);
 45             JSONUtil.returnJSON(request, response, jsonObjOut);
 46         }
 47         
 48         // 显示单个用户
 49         if (action.equals("getById")) {
 50             int id = Integer.parseInt(request.getParameter("id"));
 51             UserService userService = new UserServiceImpl();
 52             User user = userService.getById(id);
 53             
 54             // 返回JSON数据格式
 55             JSONObject jsonObjOut = new JSONObject();
 56             jsonObjOut.put("user", user);
 57             JSONUtil.returnJSON(request, response, jsonObjOut);
 58         }
 59     }
 60     
 61     protected void doPost(HttpServletRequest request, HttpServletResponse response)
 62             throws ServletException, IOException {
 63         // 获取JSON数据
 64         JSONObject jsonObjIn = JSONUtil.getJSON(request, response);
 65 
 66         User user = new User();
 67         user.setAccount(jsonObjIn.getString("account"));
 68         user.setPassword(jsonObjIn.getString("password"));
 69         user.setName(jsonObjIn.getString("name"));
 70         user.setInfo(jsonObjIn.getString("info"));
 71         
 72         UserService userService = new UserServiceImpl();
 73         boolean isSuccess = userService.add(user);
 74         
 75         // 返回JSON数据格式
 76         JSONObject jsonObjOut = new JSONObject();
 77         jsonObjOut.put("isSuccess", isSuccess);
 78         JSONUtil.returnJSON(request, response, jsonObjOut);
 79     }
 80     
 81     protected void doDelete(HttpServletRequest request, HttpServletResponse response)
 82             throws ServletException, IOException {
 83         // 获取JSON数据
 84         JSONObject jsonObjIn = JSONUtil.getJSON(request, response);
 85         int id = jsonObjIn.getInt("id");
 86 
 87         UserService userService = new UserServiceImpl();
 88         boolean isSuccess = userService.deleteById(id);
 89         
 90         // 返回JSON数据格式
 91         JSONObject jsonObjOut = new JSONObject();
 92         jsonObjOut.put("isSuccess", isSuccess);
 93         JSONUtil.returnJSON(request, response, jsonObjOut);
 94         
 95     }
 96     
 97     protected void doPut(HttpServletRequest request, HttpServletResponse response)
 98             throws ServletException, IOException {
 99         // 获取JSON数据
100         JSONObject jsonObjIn = JSONUtil.getJSON(request, response);
101 
102         User user = new User();
103         user.setId(jsonObjIn.getInt("id"));
104         user.setAccount(jsonObjIn.getString("account"));
105         user.setPassword(jsonObjIn.getString("password"));
106         user.setName(jsonObjIn.getString("name"));
107         user.setInfo(jsonObjIn.getString("info"));
108         
109         UserService userService = new UserServiceImpl();
110         boolean isSuccess = userService.update(user);
111         
112         // 返回JSON数据格式
113         JSONObject jsonObjOut = new JSONObject();
114         jsonObjOut.put("isSuccess", isSuccess);
115         JSONUtil.returnJSON(request, response, jsonObjOut);
116     }
117     
118 }

 

 5.View层

admin_user.jsp

  1 <%@ page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8"%>
  2 <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" 
  3   + request.getServerPort() + request.getContextPath() + "/"; %>
  4   
  5 <!Doctype html>
  6 <html>
  7 <head>
  8   <base href="<%=basePath%>">
  9   <title>用户管理</title>
 10   <meta charset="utf-8">
 11   <link rel="stylesheet" href="static/css/style.css">
 12   <link rel="stylesheet" href="static/js/jquery-ui/jquery-ui.min.css">
 13   <script src="static/js/jquery-3.3.1.min.js"></script>
 14   <script src="static/js/jquery.serializejson.min.js"></script>
 15   <script src="static/js/jquery-ui/jquery-ui.min.js"></script>
 16 </head>
 17 <body>
 18   <!-- 用户列表 -->
 19   <div class="tbl-title">用户列表</div>
 20   <button onclick="showAddUserModal()">添加新的用户</button>
 21   <table id="users" class="tbl-list">
 22     <thead>
 23       <tr>
 24         <th>账户</th>
 25         <th>密码</th>
 26         <th>用户名</th>
 27         <th>信息</th>
 28         <th>操作</th>
 29       </tr>
 30     </thead>
 31     <tbody>
 32     </tbody>
 33   </table>
 34   
 35   <!-- 添加用户模态框 -->
 36   <div id="add-user-modal" title="添加用户" style="display:none;">
 37     <form id="add-user-form">
 38       <table class="modal-tbl">
 39         <tr><td>账户</td><td><input type="text" name="account"></td></tr>
 40         <tr><td>密码</td><td><input type="password" name="password"></td></tr>
 41         <tr><td>姓名</td><td><input type="text" name="name"></td></tr>
 42         <tr><td>信息</td><td><input type="text" name="info"></td></tr>
 43       </table>
 44     </form>
 45   </div>
 46   
 47   <!--删除用户对话模态框 -->
 48   <div id="delete-user-modal" title="删除用户" style="display:none;">
 49     <p>确定删除该用户吗?</p>
 50   </div>
 51   
 52   <!-- 更新用户模态框 -->
 53   <div id="update-user-modal" title="更新用户" style="display:none;">
 54     <form id="update-user-form">
 55       <table class="modal-tbl">
 56         <tr style="display: none"><td>ID</td><td><input type="text" name="id"></td></tr>
 57         <tr><td>账户</td><td><input type="text" name="account"></td></tr>
 58         <tr><td>密码</td><td><input type="password" name="password"></td></tr>
 59         <tr><td>姓名</td><td><input type="text" name="name"></td></tr>
 60         <tr><td>信息</td><td><input type="text" name="info"></td></tr>
 61       </table>
 62     </form>
 63   </div>
 64   
 65   <!-- 提示信息模态框 -->
 66   <div id="msg-modal" title="" style="display:none">
 67     <p></p>
 68   </div>
 69   
 70   <script>
 71   // 开始
 72   $(function() {
 73     listAllUser();
 74   });
 75   
 76   // 显示所有用户
 77   function listAllUser() {
 78     $.ajax({
 79       type: "GET",
 80       url: "UserServlet?action=listAll",
 81       dataType: "json",
 82       success: function(data) {
 83         $("#users tbody").empty();  // 每次载入前先清空显示区域,防止数据重复显示
 84         var users = data.users;
 85         for (var i in users) {
 86           var user = users[i];
 87           var userStr = JSON.stringify(user);
 88           $("#users tbody").append(<tr><td> + user.account + </td>
 89             + <td> + user.password + </td>
 90             + <td> + user.name + </td>
 91             + <td> + user.info + </td>
 92             + <td><button onclick=\‘showUpdateUserModal( + userStr + )\‘>更新</button>&nbsp;
 93             + <button onclick="deleteUser( + user.id + )">删除</button></td></tr>);
 94         }
 95       },
 96       error: function() {
 97         console.log("ajax error");
 98       }
 99     });
100   }
101   
102   // 显示添加用户模态框
103   function showAddUserModal() {
104     $("#add-user-form")[0].reset();  // 每次载入前先清空表单,防止显示之前的信息
105     $("#add-user-modal").dialog({
106       resizable: false,
107       modal: true,
108       buttons: {
109         "提交": function() {
110           addUser();
111         },
112         "取消": function() {
113           $(this).dialog("close");
114         },
115       },
116     });
117   }
118   
119   // 添加用户
120   function addUser() {
121     // 获取序列化表单信息
122     var user = $("#add-user-form").serializeJSON();
123     var userStr = JSON.stringify(user);
124     
125     $.ajax({
126       type: "POST",
127       url: "UserServlet",
128       data: userStr,
129       dataType: "json",
130       success: function(data) {
131         if (data.isSuccess) {
132           $("#add-user-modal").dialog("close");
133           showMsg(添加成功!);
134           listAllUser();
135         } else {
136           $("#add-user-modal").dialog("close");
137           showMsg(添加失败!);
138           listAllUser();
139         }
140       },
141       error: function() {
142         console.log("ajax error");
143       },
144     });
145   }
146   
147   // 删除用户
148   function deleteUser(id) {
149     // 将id封装为JSON格式数据
150     var data = {};
151     data.id = id;
152     var dataStr = JSON.stringify(data);
153     // 显示删除用户模态框
154     $("#delete-user-modal").dialog({
155       resizable: false,
156       modal: true,
157       buttons: {
158         "确认": function() {
159           $.ajax({
160             type: "DELETE",
161             url: "UserServlet",
162             data: dataStr,
163             dataType: "json",
164             success: function(data) {
165               if (data.isSuccess) {
166                 $("#delete-user-modal").dialog("close");
167                 showMsg(删除成功!);
168                 listAllUser();
169               } else {
170                 $("#delete-user-modal").dialog("close");
171                 showMsg(删除失败!);
172                 listAllUser();
173               }
174             },
175             error: function() {
176               console.log("ajax error");
177             },
178           });
179         },
180         "取消": function() {
181           $(this).dialog("close");
182         },
183       },
184     });
185   }
186   
187   //显示更新用户模态框
188   function showUpdateUserModal(user) {
189     $("#update-user-form")[0].reset();  // 每次载入前先清空表单,防止显示之前的信息
190     // 表单赋值
191     $("#update-user-form input[name=‘id‘]").val(user.id);
192     $("#update-user-form input[name=‘account‘]").val(user.account);
193     $("#update-user-form input[name=‘password‘]").val(user.password);
194     $("#update-user-form input[name=‘name‘]").val(user.name);
195     $("#update-user-form input[name=‘info‘]").val(user.info);
196     
197     $("#update-user-modal").dialog({
198       resizable: false,
199       modal: true,
200       buttons: {
201         "提交": function() {
202           updateUser();
203         },
204         "取消": function() {
205           $(this).dialog("close");
206         },
207       },
208     });
209   }
210   
211   // 更新用户
212   function updateUser() {
213     // 获取序列化表单信息
214     var user = $("#update-user-form").serializeJSON();
215     var userStr = JSON.stringify(user);
216     
217     $.ajax({
218       type: "PUT",
219       url: "UserServlet",
220       data: userStr,
221       contentType: application/json;charset=utf-8,
222       dataType: "json",
223       success: function(data) {
224         if (data.isSuccess) {
225           $("#update-user-modal").dialog("close");
226           showMsg(更新成功!);
227           listAllUser();
228         } else {
229           $("#update-user-modal").dialog("close");
230           showMsg(更新失败!);
231           listAllUser();
232         }
233       },
234       error: function() {
235         console.log("ajax error");
236       },
237     });
238   }
239   
240   //显示提示信息
241   function showMsg(text) {
242     $("#msg-modal p").text(‘‘); // 每次载入前先清空显示区域,防止显示之前的信息
243     $("#msg-modal p").text(text);
244     $("#msg-modal").dialog({
245       modal: true,
246     });
247     // 2s后消失
248     setTimeout(function() {
249       $("#msg-modal").dialog("close")
250     },2000);
251   }
252   </script>
253 </body>
254 </html>

 

6.工具类

DBUtil.java

 1 package util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 
 6 public class DBUtil {
 7     
 8     private static String Driver = "com.mysql.jdbc.Driver";
 9     private static String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8";
10     private static String user = "root";
11     private static String psd = "123456";
12     private static Connection conn = null;
13     
14     // 连接数据库
15     public static Connection getConnection() {
16         if (conn == null) {
17             try {
18                 Class.forName(Driver);
19                 conn = DriverManager.getConnection(url, user, psd);
20                 System.out.println("开始数据库连接");
21             } catch (Exception e) {
22                 e.printStackTrace();
23             }
24         }
25         return conn;
26     }
27     
28     // 关闭数据库连接
29     public static void CloseConnection() {
30         if (conn != null) {
31             try {
32                 conn.close();
33                 System.out.println("关闭数据库连接");
34             } catch (Exception e) {
35                 e.printStackTrace();
36             }  
37         }
38     }
39 }

 

JSONUtil.java

技术图片
 1 package util;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.PrintWriter;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import net.sf.json.JSONObject;
12 
13 public class JSONUtil {
14     
15     // 从输入流中获取JSON数据
16     public static JSONObject getJSON (HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18         // 输入流
19         StringBuffer sb = new StringBuffer();
20         String line = null;
21         BufferedReader br = request.getReader();
22         while ((line = br.readLine()) != null) {
23             sb.append(line);
24         }
25         // 返回JSONObject
26         String jsonStr = sb.toString();
27         JSONObject jsonObj = JSONObject.fromObject(jsonStr);
28         return jsonObj;
29     }
30     
31     // 返回JSON格式的数据
32     public static void returnJSON (HttpServletRequest request, HttpServletResponse response, JSONObject jsonObj)
33             throws ServletException, IOException {
34         // 设置编码格式,解决乱码
35         response.setCharacterEncoding("utf-8");  
36 
37         PrintWriter out = response.getWriter() ;
38         out.write(jsonObj.toString());
39         out.flush();
40         out.close();
41     }
42     
43 }
View Code

 

JSP+Servlet+Ajax实现用户增删改查的例子

标签:text   java   head   manager   users   resultset   dia   mic   dal   

原文地址:https://www.cnblogs.com/liufuyi/p/10804824.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!