1. 程式人生 > >spring+springmvc+maven+mongodb

spring+springmvc+maven+mongodb

tca vax targe img 打印日誌 csdn cte limit start

1.前言

最近項目開發使用到了spring+springmvc+maven+mongodb,項目中的框架是用springboot進項開發的,對於我們中級開發人員來說,有利有弊,好處呢是springboot開發減少了很多配置文件,同時也使開發更加規範快捷,但是,不好的地方就是長此以往,我們就在碼農的道路上越走越遠。。。

所以,為了抵制碼農的身份,在工作之余自己親手由零一點一點搭建了這個框架,當然框架暫時只包含基本的東西,但是千裏之行始於足下,良好的開始就是成功的一半,我會在以後的道路上不斷進行擴展的,如果有問題,也請大家不吝賜教,我們共同進步!

2.準備環境

工欲善其事必先利其器,我們先做好前期準備工作,開發工具IntelliJ IDEA14,jdk版本是1.8,對於java環境變量配置,mongodb的安裝,maven的這邊不做過多說明,網上也有很多詳細的說明,大家可以去查詢,那麽下面我們就開始項目的搭建。

3.項目搭建

3.1創建maven項目

詳細步驟 點擊這裏

3.2 配置文件

3.2.1 maven依賴

[java] view plain copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.tl.project</groupId>
  5. <artifactId>skyLine</artifactId>
  6. <packaging>war</packaging>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>skyLine Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <!--建議我所引用包的版本集中放在這裏,這樣比較直觀-->
  11. <properties>
  12. <spring.version>4.2.5.RELEASE</spring.version>
  13. <aspectj.version>1.8.9</aspectj.version>
  14. <cglib.version>3.2.4</cglib.version>
  15. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>junit</groupId>
  20. <artifactId>junit</artifactId>
  21. <!--<version>3.8.1</version>-->
  22. <version>4.12</version>
  23. <scope>test</scope>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework</groupId>
  27. <artifactId>spring-web</artifactId>
  28. <version>${spring.version}</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework</groupId>
  32. <artifactId>spring-webmvc</artifactId>
  33. <version>${spring.version}</version>
  34. <scope>compile</scope>
  35. <!--<exclusions>-->
  36. <!--<exclusion>-->
  37. <!--<groupId>commons-logging</groupId>-->
  38. <!--<artifactId>commons-logging</artifactId>-->
  39. <!--</exclusion>-->
  40. <!--</exclusions>-->
  41. </dependency>
  42. <dependency>
  43. <groupId>commons-logging</groupId>
  44. <artifactId>commons-logging</artifactId>
  45. <version>1.2</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework</groupId>
  49. <artifactId>spring-jdbc</artifactId>
  50. <version>${spring.version}</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.springframework</groupId>
  54. <artifactId>spring-test</artifactId>
  55. <version>${spring.version}</version>
  56. <scope>test</scope>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework</groupId>
  60. <artifactId>spring-core</artifactId>
  61. <version>${spring.version}</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.springframework</groupId>
  65. <artifactId>spring-context</artifactId>
  66. <version>${spring.version}</version>
  67. </dependency>
  68. <dependency>
  69. <groupId>org.springframework</groupId>
  70. <artifactId>spring-context-support</artifactId>
  71. <version>${spring.version}</version>
  72. </dependency>
  73. <dependency>
  74. <groupId>org.mybatis</groupId>
  75. <artifactId>mybatis</artifactId>
  76. <version>3.2.7</version>
  77. </dependency>
  78. <dependency>
  79. <groupId>org.mybatis</groupId>
  80. <artifactId>mybatis-spring</artifactId>
  81. <version>1.2.2</version>
  82. </dependency>
  83. <dependency>
  84. <groupId>mysql</groupId>
  85. <artifactId>mysql-connector-java</artifactId>
  86. <version>5.1.30</version>
  87. </dependency>
  88. <!-- mongoDB支持jar -->
  89. <dependency>
  90. <groupId>org.springframework.data</groupId>
  91. <artifactId>spring-data-mongodb</artifactId>
  92. <version>1.8.4.RELEASE</version>
  93. </dependency>
  94. <dependency>
  95. <groupId>javax.servlet</groupId>
  96. <artifactId>javax.servlet-api</artifactId>
  97. <version>3.1.0</version>
  98. <scope>provided</scope>
  99. </dependency>
  100. <dependency>
  101. <groupId>javax.servlet.jsp</groupId>
  102. <artifactId>jsp-api</artifactId>
  103. <version>2.1</version>
  104. <scope>provided</scope>
  105. </dependency>
  106. <!--JSP標準標簽庫(JSTL)-->
  107. <dependency>
  108. <groupId>javax.servlet</groupId>
  109. <artifactId>jstl</artifactId>
  110. <version>1.2</version>
  111. </dependency>
  112. <dependency>
  113. <groupId>dom4j</groupId>
  114. <artifactId>dom4j</artifactId>
  115. <version>1.6.1</version>
  116. </dependency>
  117. <!--區別slf4j與log4j-->
  118. <dependency>
  119. <groupId>org.slf4j</groupId>
  120. <artifactId>jcl-over-slf4j</artifactId>
  121. <version>1.7.7</version>
  122. </dependency>
  123. <dependency>
  124. <groupId>org.slf4j</groupId>
  125. <artifactId>slf4j-api</artifactId>
  126. <version>1.7.7</version>
  127. </dependency>
  128. <dependency>
  129. <groupId>org.slf4j</groupId>
  130. <artifactId>slf4j-nop</artifactId>
  131. <version>1.7.5</version>
  132. </dependency>
  133. <dependency>
  134. <groupId>log4j</groupId>
  135. <artifactId>log4j</artifactId>
  136. <version>1.2.17</version>
  137. </dependency>
  138. </dependencies>
  139. <build>
  140. <finalName>skyLine</finalName>
  141. <plugins>
  142. <!-- 編碼和編譯和JDK版本 -->
  143. <!--解決@Override not allowed when implementing interface method報錯問題-->
  144. <plugin>
  145. <groupId>org.apache.maven.plugins</groupId>
  146. <artifactId>maven-compiler-plugin</artifactId>
  147. <version>2.3.2</version>
  148. <configuration>
  149. <source>1.8</source>
  150. <target>1.8</target>
  151. <encoding>utf8</encoding>
  152. </configuration>
  153. </plugin>
  154. </plugins>
  155. </build>
  156. </project>

3.2.2 spring-context.xml

[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/aop
  11. http://www.springframework.org/schema/aop/spring-aop.xsd">
  12. <!--開啟註解處理器-->
  13. <!--<context:annotation-config/>-->
  14. <!-- 自動檢測bean,啟用spring mvc 註解@Autowired,@Resource,@Required等
  15. <context:annotation-config /> 有了下面掃描配置後該項可以省掉-->
  16. <context:component-scan base-package="com.tl.skyLine">
  17. <!-- 排除不掃描的,controller放在子容器springmvc的配置文件中 -->
  18. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  19. </context:component-scan>
  20. <!--導入mongodb的配置文件-->
  21. <import resource="mongodb-context.xml"/>
  22. <!--僅用來測試springIoc是否成功-->
  23. <bean id="test" class="com.tl.skyLine.controller.TestSpringIocController">
  24. </bean>
  25. </beans>

3.2.3 springmvc-servlet.xml

[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/mvc
  10. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd">
  13. <!--只在springmvc容器中配置controller的掃描-->
  14. <context:component-scan base-package="com.tl.skyLine" use-default-filters="false">
  15. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  16. </context:component-scan>
  17. <!--這個是SpringMVC必須要配置的,因為它聲明了@RequestMapping、@RequestBody、@ResponseBody等。並且,該配置默認加載很多的參數綁定方法,比如json轉換解析器等。-->
  18. <mvc:annotation-driven/>
  19. <!-- 將在Controller返回的ModelAndView,加上目錄前綴/WEB-INF/views/, 文件名稱後綴.jsp -->
  20. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  21. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  22. <!--<beans:property name="prefix" value="/WEB-INF/views/"/>-->
  23. <property name="prefix" value="/pages/"/>
  24. <property name="suffix" value=".jsp"/>
  25. </bean>
  26. <!-- 對靜態資源文件的訪問-->
  27. <!--<mvc:resources mapping="/images/**" location="/WEB-INF/images/" cache-period="31556926"/>-->
  28. <!--<mvc:resources mapping="/js/**" location="/WEB-INF/js/" cache-period="31556926"/>-->
  29. <!--<mvc:resources mapping="/css/**" location="/WEB-INF/css/" cache-period="31556926"/>-->
  30. <!--由於父子容器的關系,@controller註解掃描配置在mvc中,所以啟動shiro註解也需要在子容器中引用一次-->
  31. <import resource="shiro-context.xml"/>
  32. </beans>

3.2.4 mongodb-context.xml

[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mongo="http://www.springframework.org/schema/data/mongo"
  6. xsi:schemaLocation="http://www.springframework.org/schema/context
  7. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  8. http://www.springframework.org/schema/data/mongo
  9. http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
  10. http://www.springframework.org/schema/beans
  11. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  12. <!-- 加載mongodb的屬性配置文件 -->
  13. <context:property-placeholder location="classpath:config.properties"/>
  14. <!-- 定義mongo對象,對應的是mongodb官方jar包中的Mongo,replica-set設置集群副本的ip地址和端口 -->
  15. <mongo:mongo id="mongo" replica-set="${mongo.hostport}">
  16. <!-- 一些連接屬性的設置 -->
  17. <mongo:options
  18. connections-per-host="${mongo.connectionsPerHost}"
  19. threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
  20. connect-timeout="${mongo.connectTimeout}"
  21. max-wait-time="${mongo.maxWaitTime}"
  22. auto-connect-retry="${mongo.autoConnectRetry}"
  23. socket-keep-alive="${mongo.socketKeepAlive}"
  24. socket-timeout="${mongo.socketTimeout}"
  25. slave-ok="${mongo.slaveOk}"
  26. write-number="1"
  27. write-timeout="0"
  28. write-fsync="true"/>
  29. </mongo:mongo>
  30. <!-- mongo的工廠,通過它來取得mongo實例,dbname為mongodb的數據庫名,沒有的話會自動創建 -->
  31. <mongo:db-factory dbname="skyLine" mongo-ref="mongo"/>
  32. <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  33. <constructor-arg ref="mongo"/>
  34. <constructor-arg name="databaseName" value="${mongo.database}"/>
  35. </bean>
  36. <!-- 映射轉換器,掃描back-package目錄下的文件,根據註釋,把它們作為mongodb的一個collection的映射 -->
  37. <mongo:mapping-converter base-package="com.tl.skyLine.model"/>
  38. <!-- mongodb bean的倉庫目錄,會自動掃描擴展了MongoRepository接口的接口進行註入 -->
  39. <mongo:repositories base-package="com.tl.skyLine.repository"/>
  40. </beans>

3.2.5 config.properties

[java] view plain copy
  1. #mongoDB連接配置
  2. mongo.hostport=127.0.0.1:27017
  3. mongo.connectionsPerHost=8
  4. mongo.threadsAllowedToBlockForConnectionMultiplier=4
  5. #連接超時時間
  6. mongo.connectTimeout=1000
  7. #等待時間
  8. mongo.maxWaitTime=1500
  9. mongo.autoConnectRetry=true
  10. mongo.socketKeepAlive=true
  11. #Socket超時時間
  12. mongo.socketTimeout=1500
  13. mongo.slaveOk=true
  14. #數據庫名稱
  15. mongo.database=skyLine

3.2.7 logging.properties

這個主要是為tomcat在控制臺增加報錯日誌信息,方便項目搭建的時候調試用的:

[java] view plain copy
  1. handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
  2. ############################################################
  3. # Handler specific properties.
  4. # Describes specific configuration info for Handlers.
  5. ############################################################
  6. org.apache.juli.FileHandler.level = FINE
  7. org.apache.juli.FileHandler.directory = ${catalina.base}/logs
  8. org.apache.juli.FileHandler.prefix = error-debug.
  9. java.util.logging.ConsoleHandler.level = FINE
  10. java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter


3.2.8 log4j.properties

這個是項目打印日誌信息用的,也可配置打印在控制臺,或者打印在硬盤某個路徑下的文檔裏:

[java] view plain copy
  1. #rootCategory:默認是對整個工程生效
  2. log4j.rootCategory=INFO, stdout
  3. #日誌輸出級別,日誌信息的優先級從高到低有ERROR、WARN、 INFO、DEBUG
  4. log4j.rootLogger=info, stdout
  5. ### stdout ###
  6. #設置stdout的日誌輸出控制臺
  7. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  8. #輸出日誌到控制臺的方式,默認為System.out
  9. log4j.appender.stdout.Target=System.out
  10. #設置使用靈活布局
  11. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  12. #靈活定義輸出格式
  13. log4j.appender.stdout.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}] %l %m %n
  14. #設置other的日誌輸出控制臺
  15. log4j.appender.other=org.apache.log4j.RollingFileAppender
  16. #設置other的輸出日誌
  17. log4j.appender.other.File=${webapp.root}/WEB-INF/logs/log.log
  18. #設置other的日誌最大限制
  19. log4j.appender.other.MaxFileSize=1024KB
  20. #最多只保存20個備份文件
  21. log4j.appender.other.MaxBackupIndex=1000
  22. #輸出INFO級別以上的日誌
  23. og4j.appender.other.Threshold=INFO
  24. #設置使用靈活布局
  25. log4j.appender.other.layout=org.apache.log4j.PatternLayout
  26. #靈活定義輸出格式
  27. log4j.appender.other.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}] %l %t %m %n

輸出格式可以自己定義,我們上面定義的比較多,如果覺得控制臺打印內容過於繁瑣,可以根據需求修改,比如如果把%l去掉,這樣就不會顯示日誌發生的位置,不會打印類名,方法名了;

[java] view plain copy
  1. %m 輸出代碼中指定的消息
  2.   %p 輸出優先級,即DEBUG,INFO,WARN,ERROR,FATAL
  3.   %r 輸出自應用啟動到輸出該log信息耗費的毫秒數
  4.   %c 輸出所屬的類目,通常就是所在類的全名
  5.   %t 輸出產生該日誌事件的線程名
  6.   %n 輸出一個回車換行符,Windows平臺為“/r/n”,Unix平臺為“/n”
  7.   %d 輸出日誌時間點的日期或時間,默認格式為ISO8601,也可以在其後指定格式,比如:%d{yyy MMM dd HH:mm:ss , SSS},輸出類似:2002年10月18日 22 : 10 : 28 , 921
  8.   %l 輸出日誌事件的發生位置,包括類目名、發生的線程,以及在代碼中的行數。舉例:Testlog4.main(TestLog4.java: 10 )

3.2.9 web.xml

[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  7. <!--指定歡迎頁面-->
  8. <welcome-file-list>
  9. <welcome-file>index.jsp</welcome-file>
  10. </welcome-file-list>
  11. <!--真正的加載順序為:context-param -> listener -> filter -> servlet-->
  12. <!--<listener>-->
  13. <!--<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>-->
  14. <!--</listener>-->
  15. <!--1、在web.xml配置監聽器ContextLoaderListener-->
  16. <!--ContextLoaderListener的作用(一句話):初始化BeanFactory,並將BeanFactory設置到application中。-->
  17. <listener>
  18. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  19. </listener>
  20. <!--2、部署applicationContext的xml文件,默認的路徑是"/WEB-INF/applicationContext.xml,
  21. 如果是要自定義文件名可以在web.xml裏加入contextConfigLocation這個context參數:
  22. 在<param-value> </param-value>裏指定相應的xml文件名,如果有多個xml文件,可以寫在一起並以“,”號分隔。
  23. 也可以這樣applicationContext-*.xml采用通配符,-->
  24. <context-param>
  25. <param-name>contextConfigLocation</param-name>
  26. <param-value>classpath:spring-context.xml</param-value>
  27. </context-param>
  28. <!--Spring log4j Config loader-->
  29. <listener>
  30. <listener-class>
  31. org.springframework.web.util.Log4jConfigListener
  32. </listener-class>
  33. </listener>
  34. <context-param>
  35. <param-name>log4jConfigLocation</param-name>
  36. <param-value>classpath:log4j.properties</param-value>
  37. </context-param>
  38. <!-- 防止Spring內存溢出監聽器 -->
  39. <!--<listener>-->
  40. <!--<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>-->
  41. <!--</listener>-->
  42. <!--通過 EnvironmentLoaderListener 這個監聽器來初始化 SecurityManager-->
  43. <!--<listener>-->
  44. <!--<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>-->
  45. <!--</listener>-->
  46. <!--使用Spring MVC,配置DispatcherServlet是第一步。DispatcherServlet是一個Servlet,
  47. 所以可以配置多個DispatcherServlet-->
  48. <servlet>
  49. <servlet-name>springMVC</servlet-name>
  50. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  51. <init-param>
  52. <param-name>contextConfigLocation</param-name>
  53. <param-value>classpath:springmvc-servlet.xml</param-value>
  54. </init-param>
  55. <!--是啟動順序,讓這個Servlet隨Servletp容器一起啟動。-->
  56. <load-on-startup>1</load-on-startup>
  57. </servlet>
  58. <servlet-mapping>
  59. <servlet-name>springMVC</servlet-name>
  60. <url-pattern>/</url-pattern>
  61. </servlet-mapping>
  62. <!-- 在Spring框架中是如何解決從頁面傳來的字符串的編碼問題的呢?
  63. 下面我們來看看Spring框架給我們提供過濾器CharacterEncodingFilter
  64. 這個過濾器就是針對於每次瀏覽器請求進行過濾的,然後再其之上添加了父類沒有的功能即處理字符編碼。
  65. 其中encoding用來設置編碼格式,forceEncoding用來設置是否理會 request.getCharacterEncoding()方法,設置為true則強制覆蓋之前的編碼格式。-->
  66. <filter>
  67. <filter-name>encodingFilter</filter-name>
  68. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  69. <init-param>
  70. <param-name>encoding</param-name>
  71. <param-value>UTF-8</param-value>
  72. </init-param>
  73. <init-param>
  74. <param-name>forceEncoding</param-name>
  75. <param-value>true</param-value>
  76. </init-param>
  77. </filter>
  78. <filter-mapping>
  79. <filter-name>encodingFilter</filter-name>
  80. <url-pattern>/*</url-pattern>
  81. </filter-mapping>
  82. <servlet-mapping>
  83. <servlet-name>default</servlet-name>
  84. <url-pattern>*.html</url-pattern>
  85. </servlet-mapping>
  86. <error-page> <!--當系統出現404錯誤,跳轉到頁面nopage.html-->
  87. <error-code>404</error-code>
  88. <location>/noPage.jsp</location>
  89. </error-page>
  90. <session-config><!--會話超時配置,單位分鐘-->
  91. <session-timeout>360</session-timeout>
  92. </session-config>
  93. </web-app>

3.3 User類

[java] view plain copy
  1. package com.tl.skyLine.model;
  2. import org.springframework.data.annotation.Id;
  3. import org.springframework.data.mongodb.core.mapping.Document;
  4. /**
  5. * 系統操作人員
  6. */
  7. @Document(collection = "sky.user")
  8. public class User {
  9. @Id
  10. private String id;
  11. private String username;
  12. private String password;
  13. public String getId() {
  14. return id;
  15. }
  16. public void setId(String id) {
  17. this.id = id;
  18. }
  19. public String getUsername() {
  20. return username;
  21. }
  22. public void setUsername(String username) {
  23. this.username = username;
  24. }
  25. public String getPassword() {
  26. return password;
  27. }
  28. public void setPassword(String password) {
  29. this.password = password;
  30. }
  31. }

3.4 數據層操作dao

userDao

[java] view plain copy
  1. package com.tl.skyLine.repository;
  2. import com.tl.skyLine.model.User;
  3. import java.util.List;
  4. /**
  5. * UserDao
  6. * Created by tl on 17/2/13.
  7. */
  8. public interface UserDao {
  9. /**
  10. * 查詢所有數據
  11. *
  12. * @return
  13. */
  14. List<User> findAll();
  15. /**
  16. * 用於分頁查詢
  17. *
  18. * @param skip(第一個坐標為0)
  19. * @param limit
  20. * @return
  21. */
  22. List<User> findList(int skip, int limit);
  23. /**
  24. * 保存用戶
  25. *
  26. * @param user
  27. */
  28. void store(User user);
  29. /**
  30. * 根據id查詢
  31. *
  32. * @param id
  33. * @return
  34. */
  35. User findOne(String id);
  36. /**
  37. * 根據用戶名查詢
  38. *
  39. * @param username
  40. * @return
  41. */
  42. User findOneByUsername(String username);
  43. /**
  44. * 更新
  45. *
  46. * @param user
  47. */
  48. void updateFirst(User user);
  49. /**
  50. * 刪除
  51. *
  52. * @param ids
  53. */
  54. void delete(String... ids);
  55. }

userDaoImpl

[java] view plain copy
  1. package com.tl.skyLine.repository;
  2. import com.tl.skyLine.model.User;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.domain.Sort;
  5. import org.springframework.data.domain.Sort.Direction;
  6. import org.springframework.data.domain.Sort.Order;
  7. import org.springframework.data.mongodb.core.MongoTemplate;
  8. import org.springframework.data.mongodb.core.query.Criteria;
  9. import org.springframework.data.mongodb.core.query.Query;
  10. import org.springframework.data.mongodb.core.query.Update;
  11. import org.springframework.stereotype.Service;
  12. import java.util.List;
  13. /**
  14. * UserDaoImpl
  15. * Created by tl on 17/2/13.
  16. */
  17. @Service
  18. public class UserDaoImpl implements UserDao {
  19. //MongoTemplate是數據庫和代碼之間的接口,對數據庫的操作都在它裏面
  20. @Autowired
  21. private MongoTemplate mongoTemplate;
  22. @Override
  23. public List<User> findAll() {
  24. return this.mongoTemplate.find(new Query(), User.class);
  25. }
  26. @Override
  27. public List<User> findList(int skip, int limit) {
  28. Query query = new Query();
  29. query.with(new Sort(new Order(Direction.ASC, "_id")));
  30. query.skip(skip).limit(limit);
  31. return this.mongoTemplate.find(query, User.class);
  32. }
  33. @Override
  34. public void store(User user) {
  35. mongoTemplate.save(user);
  36. }
  37. /**
  38. * Criteria.where("username").is(username)
  39. * 前一個是數據庫的字段,後一個是java類的字段
  40. *
  41. * @param username
  42. * @return
  43. */
  44. @Override
  45. public User findOneByUsername(String username) {
  46. Query query = new Query();
  47. Criteria criteria = Criteria.where("username").is(username);
  48. query.addCriteria(criteria);
  49. return this.mongoTemplate.findOne(query, User.class);
  50. }
  51. @Override
  52. public User findOne(String id) {
  53. Query query = new Query();
  54. Criteria criteria = Criteria.where("_id").is(id);
  55. query.addCriteria(criteria);
  56. return this.mongoTemplate.findOne(query, User.class);
  57. }
  58. @Override
  59. public void updateFirst(User user) {
  60. Update update = new Update();
  61. Query query = new Query();
  62. update.set("username", user.getUsername());
  63. update.set("password", user.getPassword());
  64. this.mongoTemplate.updateFirst(query.addCriteria(Criteria.where("_id").is(user.getId())), update, User.class);
  65. }
  66. @Override
  67. public void delete(String... ids) {
  68. if (ids == null || ids.length == 0) {
  69. return;
  70. }
  71. for (String id : ids) {
  72. Query query = new Query(Criteria.where("_id").is(id));
  73. this.mongoTemplate.remove(query, User.class);
  74. }
  75. }
  76. }

3.5單元測試

[java] view plain copy
  1. package com.tl.skyLine.controller;
  2. import com.tl.skyLine.TestSpringIocController;
  3. import com.tl.skyLine.model.User;
  4. import com.tl.skyLine.repository.UserDao;
  5. import org.apache.log4j.Logger;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. import org.springframework.test.context.ContextConfiguration;
  11. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  12. import javax.annotation.Resource;
  13. import java.util.List;
  14. /**
  15. * 測試springIoc是否成功
  16. * Created by tl on 17/2/11.
  17. * <p/>
  18. * 註解@ContextConfiguration表示將ApplicationContext對象註入進來,就不用像以往那樣在測試程序裏先new了,直接使用
  19. */
  20. @RunWith(SpringJUnit4ClassRunner.class)
  21. //@ContextConfiguration(locations = "classpath:spring-context.xml")
  22. @ContextConfiguration(locations = {"classpath:spring-context.xml", "classpath:springmvc-servlet.xml"})
  23. public class UserDaoTestController {
  24. // 在任何需要記錄日誌的類中
  25. private static Logger logger = Logger.getLogger(UserDaoTestController.class);
  26. @Resource
  27. private UserDao userDao;
  28. /**
  29. * 測試Spring IOC的開發環境
  30. */
  31. @Test
  32. public void springIoc() {
  33. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
  34. TestSpringIocController test = (TestSpringIocController) context.getBean("test");
  35. test.print();
  36. }
  37. @Test //測試Spring IOC的開發環境
  38. public void save() {
  39. User user = new User();
  40. user.setUsername("skyLine2");
  41. user.setPassword("7777777");
  42. userDao.store(user);
  43. User user2 = userDao.findOneByUsername("skyLine2");
  44. logger.info("-------獲取賬戶密碼:-------" + user2.getPassword());
  45. }
  46. @Test
  47. public void update() {
  48. User user = userDao.findOneByUsername("skyLine2");
  49. logger.info("-------更新之前賬戶密碼:-------" + user.getPassword());
  50. user.setPassword("9999888");
  51. userDao.updateFirst(user);
  52. logger.info("-------更新之後賬戶密碼:-------" + user.getPassword());
  53. }
  54. @Test //測試Spring IOC的開發環境
  55. public void findAll() {
  56. // List<User> lists = userDao.findAll();
  57. // for (User user : lists) {
  58. // logger.info("-------user遍歷:-------" + user.getUsername());
  59. // }
  60. List<User> lists2= userDao.findList(1,2);
  61. for (User user : lists2) {
  62. logger.info("-------user遍歷:-------" + user.getUsername());
  63. }
  64. }
  65. @Test
  66. public void delete() {
  67. userDao.delete(userDao.findOneByUsername("skyLine2").getId());
  68. }
  69. }


至此,基本的項目骨架就搭成了!

整個過程有些很多東西也是參考網上的博客,也結合自己的項目搭建起來的,萬丈高樓平地起,再大的項目也是一點點的搭建,不斷的測試,完善才完成的,在搭建項目的過程中收獲了很多,當然這個項目只是第一步,自己會不斷的完善!

另附整個項目的結構:

技術分享圖片


spring+springmvc+maven+mongodb