2020-02-17 11:04:56 登录注册 RSS

当前位置: 公理网 >> 显明公道 >> 如何利用SpringMVC+MongoDB+Maven搭建项目架构

如何利用SpringMVC+MongoDB+Maven搭建项目架构
发布时间:02-14| 来源:公理网 | 点击发表评论

最近研究了一下MongoDB的使用,总结一下如何利用SpringMVC+MongoDB+Maven搭建项目架构。
系统环境:操作系统:Windows7数据库:MongoDB3.2.0驱动包:spring3.2.11+spring-data-mongodb1.2.0项目结构:

?

?配置说明:
web.xml

?xmlversion="1.0"encoding="UTF-8"?web-appversion="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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"display-nameArchetypeCreatedWebApplication/display-name!--spring上下文监听器--context-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:spring-context.xml/param-value/context-paramfilterfilter-namecharacterEncodingFilter/filter-namefilter-classorg.springframework.web.filter.CharacterEncodingFilter/filter-classinit-paramparam-nameencoding/param-nameparam-valueUTF-8/param-value/init-paraminit-paramparam-nameforceEncoding/param-nameparam-valuetrue/param-value/init-param/filterfilter-mappingfilter-namecharacterEncodingFilter/filter-nameurl-pattern/*/url-pattern/filter-mapping!--Spring监听器--listenerlistener-classorg.springframework.web.context.ContextLoaderListener/listener-class/listener!--防止Spring内存溢出监听器--listenerlistener-classorg.springframework.web.util.IntrospectorCleanupListener/listener-class/listener!--springmvc控制转发器--!--自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为servlet-name+"-servlet.xml"--servletservlet-nameappServlet/servlet-nameservlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-classinit-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:mvc-servlet.xml/param-value/init-paramload-on-startup0/load-on-startup/servletservlet-mappingservlet-nameappServlet/servlet-nameurl-pattern//url-pattern/servlet-mappingwelcome-file-listwelcome-fileindex.jsp/welcome-file/welcome-file-list/web-app
?spring-context.xml

?xmlversion="1.0"encoding="UTF-8"?beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"!--启用springmvc内建的Jackson支持--!--设置json和response的字符编码--beanpropertyname="messageConverters"listbean/refbean="stringHttpMessageConverter"/refbean="jsonHttpMessageConverter"//list/property/beanbeanid="stringHttpMessageConverter"propertyname="supportedMediaTypes"listvaluetext/plain;charset=UTF-8/value/list/property/beanbeanid="jsonHttpMessageConverter"propertyname="supportedMediaTypes"listvaluetext/plain;charset=UTF-8/value/list/property/bean!--自动检测bean,启用springmvc注解@Autowired,@Resource,@Required等context:annotation-config/有了下面扫描配置后该项可以省掉--context:component-scanbase-package="com.luckypandadas"!--排除不扫描的--context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"//context:component-scancontext:annotation-config/!--context:annotation-config/--!--导入mongodb的配置文件--importresource="mongodb-context.xml"//beans
?mvc-servlet.xml

beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd"!--p:view--!--将在Controller返回的ModelAndView,加上目录前缀/WEB-INF/views/,文件名称后缀.jsp--beans:beanid="viewResolver"beans:propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/beans:propertyname="prefix"value="/WEB-INF/views/"/beans:propertyname="suffix"value=".jsp"//beans:bean!--对静态资源文件的访问mvc:resourcesmapping="/resources/**"location="/WEB-INF/resources/"cache-period="31556926"/--/beans
?mongodb的配置文件mongodb-context.xml

?xmlversion="1.0"encoding="UTF-8"?beansxmlns="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/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/data/mongohttp://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"!--加载mongodb的属性配置文件--context:property-placeholderlocation="classpath:config.properties"/!--定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口--mongo:mongoid="mongo"replica-set="${mongo.hostport}"!--一些连接属性的设置--mongo:optionsconnections-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-factorydbname="luckypandadas"mongo-ref="mongo"/beanid="mongoTemplate"constructor-argref="mongo"/constructor-argname="databaseName"value="luckypandadas"//bean!--映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射--mongo:mapping-converterbase-package="com.luckypandadas.model"/!--mongodbbean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入--mongo:repositoriesbase-package="com.luckypandadas"//beans
?mongodb的属性配置文件config.properties

#mongoDB连接配置mongo.hostport=127.0.0.1:27017mongo.connectionsPerHost=8mongo.threadsAllowedToBlockForConnectionMultiplier=4#连接超时时间mongo.connectTimeout=1000#等待时间mongo.maxWaitTime=1500mongo.autoConnectRetry=truemongo.socketKeepAlive=true#Socket超时时间mongo.socketTimeout=1500mongo.slaveOk=true
?
编写测试:
packagecom.luckypandadas.dao;importcom.luckypandadas.common.base.IBaseDao;importcom.luckypandadas.common.base.PageVo;importcom.luckypandadas.model.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.core.query.Update;importorg.springframework.stereotype.Repository;importjava.util.List;/***CreatedbyInnodev-E531on2015/12/23.*/@RepositorypublicclassIUserDaoimplementsIBaseDaoUser{@AutowiredprivateMongoTemplatemongoTemplate;/***修改操作**@paramentity*@throwsException*@authoryadong.zhang*/@Overridepublicvoidupdate(Userentity)throwsException{Queryquery=newQuery();query.addCriteria(newCriteria("telephone").is(entity.getTelephone()));Updateupdate=newUpdate();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函数:有则改之,无则加之**@paramentity*@throwsException*@authoryadong.zhang*/@Overridepublicvoidsave(Userentity)throwsException{this.mongoTemplate.save(entity);}/***insert的对象如果存在则不会修改之前的值,也不会重新增加**@paramentity*@throwsException*@authoryadong.zhang*/@Overridepublicvoidinsert(Userentity)throwsException{//save函数根据参数条件,调用了insert或update函数:有则改之,无则加之this.mongoTemplate.insert(entity);}/***根据手机获取单个**@paramtel*@return*@throwsException*@authoryadong.zhang*/@OverridepublicUsergetByTel(Stringtel)throwsException{Queryquery=newQuery();query.addCriteria(newCriteria("telephone").is(tel));returnthis.mongoTemplate.findOne(query,User.class);}/***删除**@paramuser*@throwsException*@authoryadong.zhang*/@Overridepublicvoiddelete(Useruser)throwsException{this.mongoTemplate.remove(user);}}注:这儿只测试增删改查publicUsergetUser(){Datenow=newDate();Useruser=newUser();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);returnuser;}
?注:以上为测试的被插入的一条记录
查询结果

?最后附上pom文件:
projectxmlns="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.0http://maven.apache.org/maven-v4_0_0.xsd"modelVersion4.0.0/modelVersiongroupIdcom.luckypandadas/groupIdartifactIdluckypandadas/artifactIdpackagingwar/packagingversion1.0-SNAPSHOT/versionnameluckypandadasMavenWebapp/nameurlhttp://maven.apache.org/urldependenciesdependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.8.2/versionscopetest/scope/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactIdversion4.0.5.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactIdversion3.2.11.RELEASE/versionscopecompile/scopeexclusionsexclusiongroupIdcommons-logging/groupIdartifactIdcommons-logging/artifactId/exclusion/exclusions/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-jdbc/artifactIdversion4.0.5.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion3.2.11.RELEASE/versionscopetest/scope/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-core/artifactIdversion4.0.5.RELEASE/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactIdversion1.2.0.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion4.0.5.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-context-support/artifactIdversion3.2.3.RELEASE/version/dependencydependencygroupIdorg.aspectj/groupIdartifactIdaspectjweaver/artifactIdversion1.8.0/version/dependencydependencygroupIdcglib/groupIdartifactIdcglib/artifactIdversion3.1/version/dependencydependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.2.7/version/dependencydependencygroupIdorg.mybatis/groupIdartifactIdmybatis-spring/artifactIdversion1.2.2/version/dependencydependencygroupIdcom.alibaba/groupIdartifactIddruid/artifactIdversion1.0.9/version/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.30/version/dependencydependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion3.1.0/versionscopeprovided/scope/dependencydependencygroupIdjavax.servlet.jsp/groupIdartifactIdjsp-api/artifactIdversion2.1/versionscopeprovided/scope/dependencydependencygroupIdnet.sf.json-lib/groupIdartifactIdjson-lib/artifactIdversion2.2.3/versionclassifierjdk15/classifier/dependencydependencygroupIdjstl/groupIdartifactIdjstl/artifactIdversion1.2/version/dependencydependencygroupIdorg.slf4j/groupIdartifactIdjcl-over-slf4j/artifactIdversion1.7.7/version/dependencydependencygroupIdorg.slf4j/groupIdartifactIdslf4j-api/artifactIdversion1.7.7/version/dependencydependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.17/version/dependency!--AnnotationMethodHandlerAdapterstart--dependencygroupIdorg.codehaus.jackson/groupIdartifactIdjackson-mapper-asl/artifactIdversion1.9.11/version/dependency!--AnnotationMethodHandlerAdapterend--dependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.3.3/version/dependencydependencygroupIdorg.jdom/groupIdartifactIdjdom/artifactIdversion1.1.3/version/dependencydependencygroupIdcom.google.zxing/groupIdartifactIdcore/artifactIdversion3.1.0/version/dependencydependencygroupIdcom.google.zxing/groupIdartifactIdjavase/artifactIdversion3.1.0/version/dependencydependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpclient/artifactIdversion4.4.1/version/dependency!--alipay--dependencygroupIdcommons-httpclient/groupIdartifactIdcommons-httpclient/artifactIdversion3.0.1/versionexclusionsexclusiongroupIdcommons-logging/groupIdartifactIdcommons-logging/artifactId/exclusion/exclusions/dependencydependencygroupIdcommons-codec/groupIdartifactIdcommons-codec/artifactIdversion1.6/version/dependencydependencygroupIddom4j/groupIdartifactIddom4j/artifactIdversion1.6.1/version/dependencydependencygroupIdjaxen/groupIdartifactIdjaxen/artifactIdversion1.1.6/version/dependency!--dependencygroupIdcom.thoughtworks.xstream/groupIdartifactIdxstream/artifactIdversion1.4.7/version/dependency--!--mongoDB支持jar--dependencygroupIdorg.springframework.data/groupIdartifactIdspring-data-mongodb/artifactIdversion1.2.0.RELEASE/version/dependency/dependenciesbuildfinalNameROOT/finalNameresourcesresourcedirectorysrc/main/java/directoryincludesinclude**/*.xml/includeinclude**/*.properties/include/includesfilteringfalse/filtering/resourceresourcedirectorysrc/main/resources/directoryincludesinclude**/*.xml/includeinclude**/*.properties/include/includesfilteringfalse/filtering/resource/resourcespluginspluginartifactIdmaven-compiler-plugin/artifactIdversion2.5.1/versionconfigurationsource1.6/sourcetarget1.6/targetencodingUTF-8/encoding/configuration/pluginpluginartifactIdmaven-surefire-plugin/artifactIdversion2.12.4/versionconfigurationincludesinclude**/*Tests.java/include/includes/configuration/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-resources-plugin/artifactIdversion2.6/versionconfigurationencodingUTF-8/encoding/configuration/plugin/plugins/build/project?:该文章已迁到我的个人网站上:点击访问




授予每个自然月内发布4篇或4篇以上原创或翻译IT博文的用户。不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!

授予每个自然周发布1篇到3篇原创IT博文的用户。本勋章将于次周周三上午根据用户上周的博文发布情况由系统自动颁发。

最新新闻

手机浏览

公理网 版权所有

公理网 Total 0.052151(s) query 6, 报料QQ:点击这里

给我发消息