為了賬號安全,請及時綁定郵箱和手機立即綁定

【干貨】Spring MVC + MongoDB + Maven搭建項目開發環境

2016.01.04 17:23 25541瀏覽

圖片描述
萌獸鎮樓!!!

引子

因為朋友幾個想開發一款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人點贊

若覺得本文不錯,就分享一下吧!

評論

相關文章推薦

正在加載中
意見反饋 幫助中心 APP下載
官方微信

舉報

0/150
提交
取消
lpl竞猜