一,项目说明
本项目使用spring springmvc mongodb maven整合的一个demo,欢迎大家预览,不足之处还请谅解. 或者给我回复.谢谢!
二,项目结构如图
三, xml配置代码如下
3.1 pom.xml 代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.junlenet</groupId>
<artifactId>mongodb-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>mongodb-demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.data.mongodb>1.9.2.RELEASE</spring.data.mongodb>
<mongodb.java.driver>3.2.2</mongodb.java.driver>
<fastjson.version>1.2.3</fastjson.version>
<spring.version>4.2.6.RELEASE</spring.version>
<jackson.version>2.7.0</jackson.version>
<junit>3.8.1</junit>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongodb.java.driver}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- json -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
</project>
3.2 web.xml 代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>mongodb-demo</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-mvc.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 配置session超时时间,单位分钟 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.3 spring.xml 代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--引入配置属性文件 -->
<!-- <context:property-placeholder location="classpath:config.properties" /> -->
<!-- 导入mongodb的配置文件 -->
<import resource="mongodb-context.xml"/>
<!-- <aop:aspectj-autoproxy /> -->
<!-- <bean id="applicationContextUtil" class="com.junlenet.common.util.ApplicationContextUtil"></bean> -->
</beans>
3.4 spring-mvc.xml 代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 自动扫描controller包下的所有类,如果@Controller注入为bean -->
<context:component-scan base-package="com.junlenet" />
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- json转换器 -->
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置多文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<!-- 上传文件大小限制为31M,31*1024*1024 -->
<value>32505856</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg>
<value>UTF-8</value>
</constructor-arg>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
3.5 mongodb-context.xml 代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongodb.properties" />
<!-- mongo对象 -->
<mongo:mongo-client id="mongo" replica-set="${mongo.hostport}">
<mongo:client-options connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}" />
</mongo:mongo-client>
<mongo:db-factory dbname="database" mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="${mongo.databaseName}" />
</bean>
</beans>
3.6 mongodb.properties 代码
mongo.hostport=127.0.0.1:27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
mongo.connectTimeout=1000
#\u7B49\u5F85\u65F6\u95F4
mongo.maxWaitTime=1500
mongo.socketKeepAlive=true
#Socket\u8D85\u65F6\u65F6\u95F4
mongo.socketTimeout=1500
mongo.databaseName=mongo_demo
四, java代码
4.1 Pager.java 代码
package com.junlenet.mongodb.demo.bo;
import java.util.List;
public class Pager {
private int pageSize = 10;
private int pageNum = 1;
private int pageCount;
private long total;
private List result;
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageCount() {
if(total>0){
pageCount = (int)(total%pageSize>0?total/pageSize+1:total/pageSize);
}
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getResult() {
return result;
}
public void setResult(List result) {
this.result = result;
}
}
4.2 UserBo.java 代码
package com.junlenet.mongodb.demo.bo;
import java.io.Serializable;
public class UserBo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2928923917001675021L;
private String userNo;
private String userName;
private String phone;
private String sex;
private String password;
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.3 UserDao.java 代码
package com.junlenet.mongodb.demo.dao;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.junlenet.mongodb.demo.bo.Pager;
import com.junlenet.mongodb.demo.bo.UserBo;
/**
* 用户DAO
* @author huweijun
* @date 2016年7月7日 下午8:49:18
*/
@Repository
public class UserDao {
/**
* 操作mongodb的类,可以参考api
*/
@Autowired
private MongoTemplate mongoTemplate;
/**
* 保存用户信息
* @param userBo
* @return
* @author huweijun
* @date 2016年7月7日 下午8:27:37
*/
public UserBo save(UserBo userBo) {
mongoTemplate.save(userBo);
return userBo;
}
/**
* 获取所有集合的名称
* @return
* @author huweijun
* @date 2016年7月7日 下午8:27:28
*/
public Set<String> getCollectionNames() {
Set<String> collections = mongoTemplate.getCollectionNames();
return collections;
}
/**
* 分页查询数据
* @param userBo
* @param pager
* @return
* @author huweijun
* @date 2016年7月7日 下午8:27:47
*/
public Pager selectPage(UserBo userBo,Pager pager){
Query query = new Query();
query.skip((pager.getPageNum()-1)*pager.getPageSize());
query.limit(pager.getPageSize());
/*Criteria criteria = new Criteria();
query.addCriteria(criteria);*/
long total = mongoTemplate.count(query, UserBo.class);
List<UserBo> users = mongoTemplate.find(query, UserBo.class);
pager.setResult(users);
pager.setTotal(total);
return pager;
}
}
4.4 UserService.java 代码
package com.junlenet.mongodb.demo.service;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.junlenet.mongodb.demo.bo.Pager;
import com.junlenet.mongodb.demo.bo.UserBo;
import com.junlenet.mongodb.demo.dao.UserDao;
/**
* 用户service
* @author huweijun
* @date 2016年7月7日 下午8:48:32
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
public UserBo save(UserBo userBo){
userBo = userDao.save(userBo);
return userBo;
}
public Set<String> getCollectionNames() {
return userDao.getCollectionNames();
}
public Pager selectPage(UserBo userBo,Pager pager){
return userDao.selectPage(userBo, pager);
}
}
4.5 IndexController.java 代码
package com.junlenet.mongodb.demo.controller;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.junlenet.mongodb.demo.bo.Pager;
import com.junlenet.mongodb.demo.bo.UserBo;
import com.junlenet.mongodb.demo.service.UserService;
/**
* demo 控制器
* @author huweijun
* @date 2016年7月7日 下午8:45:08
*/
@Controller
@Scope("prototype")
@RequestMapping("indexController")
public class IndexController {
//访问地址: http://127.0.0.1:8080/mongodb-demo/indexController/index.do
@Autowired
private UserService userService;
@RequestMapping("index")
public @ResponseBody String index(ModelMap modelMap) {
UserBo userBo = new UserBo();
userBo.setPassword("junlenet");
userBo.setPhone("130279814XX");
userBo.setSex("男");
userBo.setUserName("www.junlenet.com");
userBo.setUserNo("1000524100250");
userBo = userService.save(userBo);
Set<String> collections = userService.getCollectionNames();
for (String str : collections) {
System.out.println(str);
}
Pager pager = userService.selectPage(userBo, new Pager());
List<UserBo> users = pager.getResult();
for (UserBo user : users) {
System.out.println(JSONObject.toJSONString(user));
}
return JSON.toJSONString(pager);
}
}
到此为止,代码都贴完了.
运行项目, 访问地址为:
http://127.0.0.1:8080/mongodb-demo/indexController/index.do
更多信息请访问:
点击打开链接
源码下载地址:
点击打开链接