为了账号安全,请及时绑定邮箱和手机立即绑定

【干货】Spring MVC + MongoDB + Maven搭建项目开发环境

标签:
Java MongoDB

图片描述
萌兽镇楼!!!

引子

因为朋友几个想开发一款app,数据库不想用mysql,所以前些天学了下mongo,顺便研究了一下如何用SpringMVC + MongoDB + Maven 搭建开发环境,今天整理下,供各位有需的慕慕查看...

项目相关参数:

操作系统:Windows 7
数据库:MongoDB 3.2.0
驱动包:spring 3.2.11 + spring-data-mongodb 1.2.0
IDE:Idea

项目结构
图片描述

配置说明:
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Archetype Created Web Application</display-name>
    <!--spring上下文监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml</param-value>
    </context-param>

    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!-- springmvc控制转发器-->
    <!-- 自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为<servlet-name>+"-servlet.xml" -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/js/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/css/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

spring-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:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 启用spring mvc 内建的Jackson支持  -->
    <!-- 设置json和response的字符编码 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                <ref bean="stringHttpMessageConverter" />
                <ref bean="jsonHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 自动检测bean,启用spring mvc 注解@Autowired,@Resource,@Required等 <context:annotation-config /> 有了下面扫描配置后该项可以省掉-->
    <context:component-scan base-package="com.luckypandadas">
        <!-- 排除不扫描的 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- <context:annotation-config />-->
    <context:annotation-config />

    <!-- 非注解形式
    <bean id="logInterceptor" class="com.luckypandadas.common.annotation.LoggerAnnotationInterceptor"></bean>
    <aop:config>
        <aop:pointcut expression="execution(public * com.luckypandadas.service..*.*(..))"
                      id="servicePointcut"/>
        <aop:aspect id="logAspect" ref="logInterceptor">
            <aop:before method="before"  pointcut-ref="servicePointcut" />
        </aop:aspect>

    </aop:config>-->
    <!-- 开始aop支持,动态代理支持 -->
    <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />

    <!-- 导入mongodb的配置文件 -->
    <import resource="mongodb-context.xml"/>
</beans>

mvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- p:viewClass="org.springframework.web.servlet.view.JstlView" -->
    <!-- 将在Controller返回的ModelAndView,加上目录前缀/WEB-INF/views/, 文件名称后缀.jsp -->
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <beans:property name="prefix" value="/WEB-INF/views/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>
    <!-- 对静态资源文件的访问
    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache-period="31556926"/>
    -->
    <!-- 在xml配置了这个标签后,spring可以自动去扫描base-package下面或者子包下面的java文件, 如果扫描到有@Component
            @Controller@Service等这些注解的类,则把这些类注册为bean -->
    <context:component-scan base-package="com.luckypandadas">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!-- 自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter
        两个bean,是spring MVC为@Controllers分发请求所必须的 -->
    <mvc:annotation-driven />
</beans>

config.properties(mongodb链接参数)

#mongoDB连接配置
mongo.hostport=127.0.0.1:27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
#Socket超时时间
mongo.socketTimeout=1500
mongo.slaveOk=true

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-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 加载mongodb的属性配置文件 -->
    <context:property-placeholder location="classpath:config.properties" />

    <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
    <mongo:mongo id="mongo" replica-set="${mongo.hostport}">
        <!-- 一些连接属性的设置 -->
        <mongo:options
                connections-per-host="${mongo.connectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                connect-timeout="${mongo.connectTimeout}"
                max-wait-time="${mongo.maxWaitTime}"
                auto-connect-retry="${mongo.autoConnectRetry}"
                socket-keep-alive="${mongo.socketKeepAlive}"
                socket-timeout="${mongo.socketTimeout}"
                slave-ok="${mongo.slaveOk}"
                write-number="1"
                write-timeout="0"
                write-fsync="true"/>
    </mongo:mongo>
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
    <mongo:db-factory dbname="luckypandadas" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="luckypandadas" />
    </bean>
    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
    <mongo:mapping-converter base-package="com.luckypandadas.model" />

    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
    <mongo:repositories base-package="com.luckypandadas" />

</beans>

编写测试:

package com.luckypandadas.dao;
import com.luckypandadas.common.base.IBaseDao;
import com.luckypandadas.common.base.PageVo;
import com.luckypandadas.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * Created by Innodev-E531 on 2015/12/23.
 */
@Repository
public class IUserDao implements IBaseDao<User> {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 修改操作
     *
     * @param entity
     * @throws Exception
     * @author yadong.zhang
     */
    @Override
    public void update(User entity) throws Exception {
        Query query = new Query();
        query.addCriteria(new Criteria("telephone").is(entity.getTelephone()));
        Update update = new Update();
        update.set("telephone", entity.getTelephone());
        update.set("email", entity.getEmail());
        update.set("nickname", entity.getNickname());
        update.set("lastLoginTime", entity.getLastLoginTime());
        update.set("updateTime", entity.getUpdatedTime());
        update.set("gender", entity.getGender());
        update.set("picturePath", entity.getPicturePath());
        this.mongoTemplate.updateFirst(query, update, User.class);
    }
    /**
     * save函数根据参数条件,调用了insert或update函数:有则改之,无则加之
     *
     * @param entity
     * @throws Exception
     * @author yadong.zhang
     */
    @Override
    public void save(User entity) throws Exception {
        this.mongoTemplate.save(entity);
    }
    /**
     * insert的对象如果存在则不会修改之前的值,也不会重新增加
     *
     * @param entity
     * @throws Exception
     * @author yadong.zhang
     */
    @Override
    public void insert(User entity) throws Exception {
        //save函数根据参数条件,调用了insert或update函数:有则改之,无则加之
        this.mongoTemplate.insert(entity);
    }
    /**
     * 根据手机获取单个
     *
     * @param tel
     * @return
     * @throws Exception
     * @author yadong.zhang
     */
    @Override
    public User getByTel(String tel) throws Exception {
        Query query = new Query();
        query.addCriteria(new Criteria("telephone").is(tel));
        return this.mongoTemplate.findOne(query, User.class);
    }
    /**
     * 删除
     *
     * @param user
     * @throws Exception
     * @author yadong.zhang
     */
    @Override
    public void delete(User user) throws Exception {
        this.mongoTemplate.remove(user);
    }
}

注:这儿只测试增删改查

public User getUser(){
        Date now = new Date();
        User user = new User();
        user.setTelephone("12322241");
        user.setEmail("843977358@qq.com");
        user.setNickname("七彩狼222");
        user.setPassword("123456.");
        user.setId("123413");
        user.setStatus(Constants.STATUS_BLOCK);
        user.setCreatedTime(now);
        user.setUpdatedTime(now);
        user.setLastLoginTime(now);
        return user;
    }

查询结果:
图片描述
如上。。。
我的笔记
图片描述

我可以对一个人无限的好,前提是值得。 ——慕冬雪

点击查看更多内容
40人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消