Welcome to MongoDB Web Application example. Earlier in MongoDB Java Example we learned how to use MongoDB java driver in standalone application. Today we are moving forward to integrate MongoDB in Java Servlet web application.
We will create a web application where we will be manage Person data and store it in the MongoDB database. We will be able to create, read, update and delete Person records from the user interface and corresponding operations will be performed against MongoDB database.
First step is to create a dynamic web application in Eclipse and then convert it to Maven project, so that our maven based web application skeleton code is ready. Below image shows the final project structure and different components of it.
Notice that we have MongoDB java driver dependency to connect to MongoDB server, JSTL and standard jars are required for using JSTL tags in the JSP pages.
MongoDB server host and port details are configured as context parameters, rather than hardcoding them somewhere in the code. MongoDB服务器的主机和端口详细信息配置为上下文参数,而不是在代码中的某些地方对其进行硬编码。
We have single JSP page for view purposes, I have added it in the welcome file list to avoid empty page for web application home. 为了查看目的,我们只有一个JSP页面,我在欢迎文件列表中添加了它,以避免Web应用程序主页出现空白页面。
模型Bean或POJO类 (Model Bean or POJO Class)
We have Person.java class as Model class, this bean will be saved as Mongo DBObject into database.
package com.journaldev.mongodb.model;
public class Person {
// id will be used for primary key in MongoDB
// We could use ObjectId, but I am keeping it
// independent of MongoDB API classes
private String id;
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Notice that it has id attribute, this will be generated by MongoDB and it won’t be editable by user. This will serve as the primary key for MongoDB object. Notice that MongoDB record primary key is stored with “_id” key and when we retrieve it, it’s returned as ObjectId instance. For loose coupling, I am using String but we can also use ObjectId type.
Java Bean到MongoDB DBObject转换器 (Java Bean to MongoDB DBObject Converter)
We have a helper class for converting Person object to MongoDB DBObject and vice versa.
我们有一个帮助程序类,用于将Person对象转换为MongoDB DBObject,反之亦然。
PersonConverter.java
PersonConverter.java
package com.journaldev.mongodb.converter;
import org.bson.types.ObjectId;
import com.journaldev.mongodb.model.Person;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
public class PersonConverter {
// convert Person Object to MongoDB DBObject
// take special note of converting id String to ObjectId
public static DBObject toDBObject(Person p) {
BasicDBObjectBuilder builder = BasicDBObjectBuilder.start()
.append("name", p.getName()).append("country", p.getCountry());
if (p.getId() != null)
builder = builder.append("_id", new ObjectId(p.getId()));
return builder.get();
}
// convert DBObject Object to Person
// take special note of converting ObjectId to String
public static Person toPerson(DBObject doc) {
Person p = new Person();
p.setName((String) doc.get("name"));
p.setCountry((String) doc.get("country"));
ObjectId id = (ObjectId) doc.get("_id");
p.setId(id.toString());
return p;
}
}
Conversion is very simple, just take a note of converting the id attribute to ObjectId and vice versa.
转换非常简单,只需注意将id属性转换为ObjectId,反之亦然。
MongoDB DAO实施 (MongoDB DAO Implementation)
We could have created a Person DAO interface and provided MongoDB implementation, but for simplicity we have simple MongoDB DAO implementation to expose different operations we can perform for Person object in MongoDB database.
MongoClient is thread safe and internally manages it’s own connection pool. Best practice is to create an instance of it and reuse it. We should close it when the application is shut down, that makes ServletContextListener implementation best choice to initialize and destroy it.
Notice that I am using @WebListener annotation to configure it as listener class, your servlet container should support it or else you will have to use XML based configurations. I am using Apache Tomcat 7 that supports Servlet API annotations, so make sure you use compatible servlet container or change the code to use XML based configurations.
We have three servlet classes for CRUD operations, they have some validation logic to make sure input data is valid. If everything is fine with request parameters, then it’s using MongoDB DAO implementation to perform database operations and forward the request to the JSP page after setting correct attributes.
package com.journaldev.mongodb.servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.journaldev.mongodb.dao.MongoDBPersonDAO;
import com.journaldev.mongodb.model.Person;
import com.mongodb.MongoClient;
@WebServlet("/addPerson")
public class AddPersonServlet extends HttpServlet {
private static final long serialVersionUID = -7060758261496829905L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String country = request.getParameter("country");
if ((name == null || name.equals(""))
|| (country == null || country.equals(""))) {
request.setAttribute("error", "Mandatory Parameters Missing");
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
} else {
Person p = new Person();
p.setCountry(country);
p.setName(name);
MongoClient mongo = (MongoClient) request.getServletContext()
.getAttribute("MONGO_CLIENT");
MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
personDAO.createPerson(p);
System.out.println("Person Added Successfully with id="+p.getId());
request.setAttribute("success", "Person Added Successfully");
List persons = personDAO.readAllPerson();
request.setAttribute("persons", persons);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
}
}
}
EditPersonServlet.java
EditPersonServlet.java
package com.journaldev.mongodb.servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.journaldev.mongodb.dao.MongoDBPersonDAO;
import com.journaldev.mongodb.model.Person;
import com.mongodb.MongoClient;
@WebServlet("/editPerson")
public class EditPersonServlet extends HttpServlet {
private static final long serialVersionUID = -6554920927964049383L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if (id == null || "".equals(id)) {
throw new ServletException("id missing for edit operation");
}
System.out.println("Person edit requested with id=" + id);
MongoClient mongo = (MongoClient) request.getServletContext()
.getAttribute("MONGO_CLIENT");
MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
Person p = new Person();
p.setId(id);
p = personDAO.readPerson(p);
request.setAttribute("person", p);
List persons = personDAO.readAllPerson();
request.setAttribute("persons", persons);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id"); // keep it non-editable in UI
if (id == null || "".equals(id)) {
throw new ServletException("id missing for edit operation");
}
String name = request.getParameter("name");
String country = request.getParameter("country");
if ((name == null || name.equals(""))
|| (country == null || country.equals(""))) {
request.setAttribute("error", "Name and Country Can't be empty");
MongoClient mongo = (MongoClient) request.getServletContext()
.getAttribute("MONGO_CLIENT");
MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
Person p = new Person();
p.setId(id);
p.setName(name);
p.setCountry(country);
request.setAttribute("person", p);
List persons = personDAO.readAllPerson();
request.setAttribute("persons", persons);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
} else {
MongoClient mongo = (MongoClient) request.getServletContext()
.getAttribute("MONGO_CLIENT");
MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
Person p = new Person();
p.setId(id);
p.setName(name);
p.setCountry(country);
personDAO.updatePerson(p);
System.out.println("Person edited successfully with id=" + id);
request.setAttribute("success", "Person edited successfully");
List persons = personDAO.readAllPerson();
request.setAttribute("persons", persons);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
}
}
}
DeletePersonServlet.java
DeletePersonServlet.java
package com.journaldev.mongodb.servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.journaldev.mongodb.dao.MongoDBPersonDAO;
import com.journaldev.mongodb.model.Person;
import com.mongodb.MongoClient;
@WebServlet("/deletePerson")
public class DeletePersonServlet extends HttpServlet {
private static final long serialVersionUID = 6798036766148281767L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if (id == null || "".equals(id)) {
throw new ServletException("id missing for delete operation");
}
MongoClient mongo = (MongoClient) request.getServletContext()
.getAttribute("MONGO_CLIENT");
MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
Person p = new Person();
p.setId(id);
personDAO.deletePerson(p);
System.out.println("Person deleted successfully with id=" + id);
request.setAttribute("success", "Person deleted successfully");
List persons = personDAO.readAllPerson();
request.setAttribute("persons", persons);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/persons.jsp");
rd.forward(request, response);
}
}
Notice the use of @WebServlet annotation for configuring the URI pattern for each of the servlets. It will be used in JSP pages to send the request to correct servlet.
Recommended Read: JSTL Tutorial, JSP EL and JSP implicit objects.
推荐阅读 : JSTL教程 , JSP EL和JSP隐式对象 。
MongoDB Java Web应用程序测试 (MongoDB Java Web Application Test)
Our application is ready for a test drive, below screenshots show some of the response pages of different CRUD operations.
我们的应用程序已准备好进行测试驱动,以下屏幕截图显示了不同CRUD操作的一些响应页面。
Home Page
主页
Create Person Page
创建人员页面
Read Person Page
阅读人页面
Update Person Page
更新人员页面
Delete Person Page
删除人员页面
You will also find below logs in the server log file.
您还将在服务器日志文件中找到以下日志。
MongoClient initialized successfully
Person Added Successfully with id=53ea76e70364b0028f507802
Person Added Successfully with id=53ea76fd0364b0028f507803
Person edit requested with id=53ea76e70364b0028f507802
Person edited successfully with id=53ea76e70364b0028f507802
Person deleted successfully with id=53ea76fd0364b0028f507803
MongoClient closed successfully
摘要 (Summary)
This post was intended to provide a complete example of using MongoDB server as data storage, you learned how to use MongoDB java driver for CRUD operations and create a web application. Download the final project from below link and explore more.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml&q
// for循环的进化
// 菜鸟
for (var i = 0; i < Things.length ; i++) {
// Things[i]
}
// 老鸟
for (var i = 0, len = Things.length; i < len; i++) {
// Things[i]
}
// 大师
for (var i = Things.le
the idea is from:
http://blog.csdn.net/zhanxinhang/article/details/6731134
public class MaxSubMatrix {
/**see http://blog.csdn.net/zhanxinhang/article/details/6731134
* Q35
求一个矩阵中最大的二维
使用cordova可以很方便的在手机sdcard中读写文件。
首先需要安装cordova插件:file
命令为:
cordova plugin add org.apache.cordova.file
然后就可以读写文件了,这里我先是写入一个文件,具体的JS代码为:
var datas=null;//datas need write
var directory=&
SELECT cust_id,
SUM(price) as total
FROM orders
WHERE status = 'A'
GROUP BY cust_id
HAVING total > 250
db.orders.aggregate( [
{ $match: { status: 'A' } },
{
$group: {