返回顶部

一缕半夏微光

温柔半两,从容一生

导航

MongoDB+Web->简易的增删改查

一、效果如下:

二、工程目录如下:

三、代码如下:

MongoDB.java

  1 package mongodb;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import org.bson.Document;
  6 import com.mongodb.MongoClient;
  7 import com.mongodb.MongoClientOptions;
  8 import com.mongodb.ServerAddress;
  9 import com.mongodb.client.FindIterable;
 10 import com.mongodb.client.MongoCollection;
 11 import com.mongodb.client.MongoCursor;
 12 import com.mongodb.client.MongoDatabase;
 13 import com.mongodb.client.model.Filters;
 14 import com.mongodb.client.result.UpdateResult;
 15 
 16 import util.User;
 17 
 18 public class MongoDB {
 19     // 连接数据库
 20     @SuppressWarnings("unused")
 21     public static void Connection() {
 22         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
 23         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
 24         // 获取操作数据库
 25         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
 26         System.out.println("MongoDB数据库连接成功");
 27         // 获取集合。后面的操作,大部分都是基于集合操作
 28         MongoCollection<Document> contections = db.getCollection("user");
 29     }
 30 
 31     // 插入数据
 32     public boolean add(User user) {
 33         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
 34         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
 35         // 获取操作数据库
 36         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
 37         System.out.println("MongoDB数据库连接成功");
 38         // 获取集合。后面的操作,大部分都是基于集合操作
 39         MongoCollection<Document> contections = db.getCollection("user");
 40         boolean judge = false;
 41         try {
 42             // 插入
 43             contections.insertOne(
 44                     new Document("id", 1).append("name", user.getName()).append("password", user.getPassword())
 45                             .append("sex", user.getSex()).append("phone", user.getPhone()));
 46             System.out.println("插入成功");
 47             judge = true;
 48         } catch (Exception e) {
 49             System.out.println("插入失败");
 50             judge = false;
 51             e.printStackTrace();
 52         }
 53         return judge;
 54     }
 55 
 56     // 查询数据
 57     public List<User> find() {
 58 
 59         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
 60         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
 61         // 获取操作数据库
 62         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
 63         System.out.println("MongoDB数据库连接成功");
 64         // 获取集合。后面的操作,大部分都是基于集合操作
 65         MongoCollection<Document> contections = db.getCollection("user");
 66 
 67         List<User> list = new ArrayList<>();
 68         User user = null;
 69         try {
 70             FindIterable<Document> result = contections.find();
 71 
 72             for (Document document : result) {
 73                 String name = document.getString("name");
 74                 String password = document.getString("password");
 75                 String sex = document.getString("sex");
 76                 String phone = document.getString("phone");
 77                 user = new User(name, password, sex, phone);
 78                 list.add(user);
 79             }
 80 
 81         } catch (Exception e) {
 82             e.printStackTrace();
 83         }
 84         return list;
 85     }
 86 
 87     // 删除
 88     public boolean delete(String name) {
 89         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
 90         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
 91         // 获取操作数据库
 92         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
 93         System.out.println("MongoDB数据库连接成功");
 94         // 获取集合。后面的操作,大部分都是基于集合操作
 95         MongoCollection<Document> contections = db.getCollection("user");
 96         boolean judge = false;
 97         try {
 98             Document document = new Document();
 99             document.put("name", name);
100             contections.deleteOne(document);
101             judge = true;
102         } catch (Exception e) {
103             e.printStackTrace();
104         }
105 
106         return judge;
107     }
108 
109     // 修改
110     public List<User> alter(String name) {
111         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
112         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
113         // 获取操作数据库
114         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
115         System.out.println("MongoDB数据库连接成功");
116         // 获取集合。后面的操作,大部分都是基于集合操作
117         MongoCollection<Document> contections = db.getCollection("user");
118 
119         List<User> list = new ArrayList<>();
120         User user = null;
121         try {
122             MongoCursor<Document> result = contections.find().filter(Filters.eq("name", name)).iterator();
123 
124             while (result.hasNext()) {
125                 Document document = result.next();
126                 String namee = document.getString("name");
127                 String password = document.getString("password");
128                 String sex = document.getString("sex");
129                 String phone = document.getString("phone");
130                 user = new User(namee, password, sex, phone);
131                 list.add(user);
132                 System.out.println(namee);
133             }
134 
135         } catch (Exception e) {
136             e.printStackTrace();
137         }
138         return list;
139     }
140 
141     // 修改——更新
142     @SuppressWarnings("unused")
143     public boolean update(User user, String judgename) {
144         MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).build();
145         MongoClient monGoClient = new MongoClient(new ServerAddress("localhost", 27017), option);
146         // 获取操作数据库
147         MongoDatabase db = monGoClient.getDatabase("mongodb_crud");
148         System.out.println("MongoDB数据库连接成功");
149         // 获取集合。后面的操作,大部分都是基于集合操作
150         MongoCollection<Document> contections = db.getCollection("user");
151         boolean judge = false;
152         try {
153             UpdateResult update = contections.updateOne(Filters.eq("name", judgename),
154                     new Document("$set", new Document("name", user.getName()).append("password", user.getPassword())
155                             .append("sex", user.getSex()).append("phone", user.getPhone())));
156             judge = true;
157         } catch (Exception e) {
158             e.printStackTrace();
159         }
160         return judge;
161     }
162 }

Servlet.java

  1 package servlet;
  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 import mongodb.MongoDB;
 12 import util.User;
 13 
 14 /**
 15  * Servlet implementation class Servlet
 16  */
 17 @WebServlet("/Servlet")
 18 public class Servlet extends HttpServlet {
 19     private static final long serialVersionUID = 1L;
 20 
 21     /**
 22      * @see HttpServlet#HttpServlet()
 23      */
 24     public Servlet() {
 25         super();
 26         // TODO Auto-generated constructor stub
 27     }
 28 
 29     MongoDB dao = new MongoDB();
 30 
 31     public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 32         response.setCharacterEncoding("UTF-8");
 33         request.setCharacterEncoding("UTF-8");
 34 
 35         String name = request.getParameter("name");
 36         String password = request.getParameter("password");
 37         String sex = request.getParameter("sex");
 38         String phone = request.getParameter("phone");
 39 
 40         System.out.println("name:" + name);
 41         System.out.println("password:" + password);
 42         System.out.println("sex:" + sex);
 43         System.out.println("phone:" + phone);
 44 
 45         User user = new User(name, password, sex, phone);
 46 
 47         if (dao.add(user)) {
 48             System.out.println("添加成功");
 49             request.getRequestDispatcher("main.jsp").forward(request, response);
 50         } else {
 51             System.out.println("添加失败");
 52             request.getRequestDispatcher("add.jsp").forward(request, response);
 53         }
 54 
 55     }
 56 
 57     public void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 58         response.setCharacterEncoding("UTF-8");
 59         request.setCharacterEncoding("UTF-8");
 60 
 61         List<User> list = dao.find();
 62         request.setAttribute("list", list);
 63 
 64         System.out.println("查询成功");
 65         request.getRequestDispatcher("find.jsp").forward(request, response);
 66 
 67     }
 68 
 69     public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 70         response.setCharacterEncoding("UTF-8");
 71         request.setCharacterEncoding("UTF-8");
 72 
 73         List<User> list = dao.find();
 74         request.setAttribute("list", list);
 75         request.getRequestDispatcher("delete.jsp").forward(request, response);
 76 
 77     }
 78 
 79     public void delete_show(HttpServletRequest request, HttpServletResponse response)
 80             throws ServletException, IOException {
 81         response.setCharacterEncoding("UTF-8");
 82         request.setCharacterEncoding("UTF-8");
 83 
 84         String name = request.getParameter("name");
 85         System.out.println("name:" + name);
 86 
 87         if (dao.delete(name)) {
 88             System.out.println("删除成功");
 89             request.getRequestDispatcher("main.jsp").forward(request, response);
 90         } else {
 91             System.out.println("删除失败");
 92             request.getRequestDispatcher("fail.jsp").forward(request, response);
 93         }
 94 
 95     }
 96 
 97     public void alter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 98         response.setCharacterEncoding("UTF-8");
 99         request.setCharacterEncoding("UTF-8");
100 
101         List<User> list = dao.find();
102         request.setAttribute("list", list);
103         request.getRequestDispatcher("alter.jsp").forward(request, response);
104 
105     }
106 
107     public void alter_show(HttpServletRequest request, HttpServletResponse response)
108             throws ServletException, IOException {
109         response.setCharacterEncoding("UTF-8");
110         request.setCharacterEncoding("UTF-8");
111 
112         String name = request.getParameter("name");
113         System.out.println("name:" + name);
114         List<User> list = dao.alter(name);
115         request.setAttribute("list", list);
116         System.out.println("进入修改界面成功");
117         request.getRequestDispatcher("update.jsp").forward(request, response);
118 
119     }
120 
121     public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
122         response.setCharacterEncoding("UTF-8");
123         request.setCharacterEncoding("UTF-8");
124 
125         String name = request.getParameter("name");
126         String judge = request.getParameter("judge");
127         String password = request.getParameter("password");
128         String sex = request.getParameter("sex");
129         String phone = request.getParameter("phone");
130 
131         System.out.println("name:" + name);
132         System.out.println("judge:" + judge);
133         System.out.println("password:" + password);
134         System.out.println("sex:" + sex);
135         System.out.println("phone:" + phone);
136 
137         User user = new User(name, password, sex, phone);
138 
139         if (dao.update(user, judge)) {
140             System.out.println("修改成功");
141             request.getRequestDispatcher("main.jsp").forward(request, response);
142         } else {
143             System.out.println("修改失败");
144             request.getRequestDispatcher("fail.jsp").forward(request, response);
145         }
146 
147     }
148 
149     /**
150      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
151      *      response)
152      */
153     protected void doGet(HttpServletRequest request, HttpServletResponse response)
154             throws ServletException, IOException {
155         // TODO Auto-generated method stub
156         response.setCharacterEncoding("UTF-8");
157         request.setCharacterEncoding("UTF-8");
158         System.out.println("进入Servlet");
159         String method = request.getParameter("method");
160         System.out.println(method);
161         if ("add".equals(method)) {
162             add(request, response);
163         } else if ("find".equals(method)) {
164             find(request, response);
165         } else if ("delete".equals(method)) {
166             delete(request, response);
167         } else if ("delete_show".equals(method)) {
168             delete_show(request, response);
169         } else if ("alter".equals(method)) {
170             alter(request, response);
171         } else if ("alter_show".equals(method)) {
172             alter_show(request, response);
173         } else if ("update".equals(method)) {
174             update(request, response);
175         }
176     }
177 
178     /**
179      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
180      *      response)
181      */
182     protected void doPost(HttpServletRequest request, HttpServletResponse response)
183             throws ServletException, IOException {
184         // TODO Auto-generated method stub
185         doGet(request, response);
186     }
187 
188 }

User.java

 1 package util;
 2 
 3 public class User {
 4     private String name;//用户名
 5     private String password;//密码
 6     private String sex;//性别
 7     private String phone;//电话
 8     
 9     public String getName() {
10         return name;
11     }
12     public void setName(String name) {
13         this.name = name;
14     }
15     public String getPassword() {
16         return password;
17     }
18     public void setPassword(String password) {
19         this.password = password;
20     }
21     public String getSex() {
22         return sex;
23     }
24     public void setSex(String sex) {
25         this.sex = sex;
26     }
27     public String getPhone() {
28         return phone;
29     }
30     public void setPhone(String phone) {
31         this.phone = phone;
32     }
33     
34     public User() {super();}
35     public User(String name,String password,String sex,String phone) {
36         super();
37         this.name=name;
38         this.password=password;
39         this.sex=sex;
40         this.phone=phone;
41     }
42     
43     @Override
44     public String toString() {
45         return "User{" +
46                 "name=" + name +
47                 ", password='" + password + '\'' +
48                 ", sex=" + sex +
49                 ", phone='" + phone + '\'' +
50                 '}';
51     }
52 
53 }

add.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>增加页面</title>
 8 </head>
 9 <body>
10 <form action="Servlet?method=add" method="post" >
11     <table align="center">
12         <tr>
13             <td>姓名:</td>
14             <td>
15                 <input type="text" id="name" name="name" placeholder="请输入姓名" >
16             </td>
17         </tr>
18         <tr>
19             <td>密码:</td>
20             <td>
21                 <input type="password" id="password" name="password" placeholder="请输入密码">
22             </td>
23         </tr>
24         <tr>
25             <td>性别:</td>
26             <td>
27                 <input type="radio" id="sex" name="sex" checked="checked" value="男">28                 <input type="radio" id="sex" name="sex" value="女">29             </td>
30         </tr>
31         <tr>
32             <td>电话:</td>
33             <td>
34                 <input type="text" id="phone" name="phone" placeholder="请输入电话">
35             </td>
36         </tr>
37     </table>
38     <table align="center">
39         <tr style="text-align: center">
40             <td><input type="submit" value="增加"></td>
41             <td><input type="reset" value="重置"></td>
42             <td><input type="button" value="返回" onclick="window.location.href='main.jsp'"></td>
43         </tr>
44     </table>
45 </form>
46 </body>
47 </html>

alter.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>修改界面</title>
 9 </head>
10 <body>
11 <form action="Servlet?method=alter" method="post" >
12     <table align="center">
13         <tr>
14             <th>姓名</th>
15             <th>密码</th>
16             <th>性别</th>
17             <th>电话</th>
18         </tr>
19         <c:forEach items="${list}" var="user">
20             <tr>
21                 <td>${user.name}</td>
22                 <td>${user.password}</td>
23                 <td>${user.sex}</td>
24                 <td>${user.phone}</td>
25                 <td><a href="Servlet?method=alter_show&name=${user.name}">修改</a></td>
26             </tr>
27         </c:forEach>
28     </table>
29 </form>
30 </body>
31 </html>

delete.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>删除界面</title>
 9 </head>
10 <body>
11 <form action="Servlet?method=delete" method="post" >
12     <table align="center">
13         <tr>
14             <th>姓名</th>
15             <th>密码</th>
16             <th>性别</th>
17             <th>电话</th>
18         </tr>
19         <c:forEach items="${list}" var="user">
20             <tr>
21                 <td>${user.name}</td>
22                 <td>${user.password}</td>
23                 <td>${user.sex}</td>
24                 <td>${user.phone}</td>
25                 <td><a href="Servlet?method=delete_show&name=${user.name}">删除</a></td>
26             </tr>
27         </c:forEach>
28     </table>
29 </form>
30 </body>
31 </html>

fail.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>失败</title>
 8 </head>
 9 <body>
10 失败
11 </body>
12 </html>

find.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>查询界面</title>
 9 </head>
10 <body>
11     <form action="Servlet?method=find" method="post">
12         <table align="center">
13             <tr>
14                 <th>姓名</th>
15                 <th>密码</th>
16                 <th>性别</th>
17                 <th>电话</th>
18             </tr>
19             <c:forEach items="${list}" var="user">
20                 <tr>
21                     <td>${user.name}</td>
22                     <td>${user.password}</td>
23                     <td>${user.sex}</td>
24                     <td>${user.phone}</td>
25                 </tr>
26             </c:forEach>
27         </table>
28     </form>
29 </body>
30 </html>

main.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>CRUD</title>
 8 </head>
 9 <body>
10 <table align="center">
11     <tr style="text-align: center">
12         <td><input type="button" value="增加" onclick="window.location.href='add.jsp'"></td>
13     </tr>
14     <tr style="text-align: center">
15         <td><button onclick="window.location.href='Servlet?method=delete'">删除</button></td>
16     </tr>
17     <tr style="text-align: center">
18         <td><button onclick="window.location.href='Servlet?method=alter'">修改</button></td>
19     </tr>
20     <tr style="text-align: center">
21         <td><button onclick="window.location.href='Servlet?method=find'">查询</button></td>
22     </tr>
23 </table>
24 
25 </body>
26 </html>

update.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>修改页面</title>
 9 </head>
10 <body>
11 <form action="Servlet?method=update" method="post" >
12     <c:forEach items="${list}" var="user">
13     <table align="center">
14         <tr>
15             <td>姓名:</td>
16             <td>
17                 <input type="text" id="name" name="name" value="${user.name}">
18                 <input type="hidden" id="judge" name="judge" value="${user.name}">
19             </td>
20         </tr>
21         <tr>
22             <td>密码:</td>
23             <td>
24                 <input type="text" id="password" name="password" value="${user.password}">
25             </td>
26         </tr>
27         <tr>
28             <td>性别:</td>
29             <td>
30                 <input type="text" id="sex" name="sex" value="${user.sex}">
31             </td>
32         </tr>
33         <tr>
34             <td>电话:</td>
35             <td>
36                 <input type="text" id="phone" name="phone" value="${user.phone}">
37             </td>
38         </tr>
39     </table>
40     <table align="center">
41         <tr style="text-align: center">
42             <td><input type="submit" value="修改"></td>
43         </tr>
44     </table>
45 </c:forEach>
46 </form>
47 </body>
48 </html>

posted on 2021-11-03 16:41  一缕半夏微光  阅读(152)  评论(0编辑  收藏  举报