1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app 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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 6 version="3.0" 7 metadata-complete="true"> 8 9 <display-name>ssm-maven-demo</display-name> 10 <welcome-file-list> 11 <welcome-file>index.jsp</welcome-file> 12 </welcome-file-list> 13 <context-param> 14 <param-name>contextConfigLocation</param-name> 15 <param-value>classpath:spring-context.xml</param-value> 16 </context-param> 17 18 <filter> 19 <filter-name>encodingFilter</filter-name> 20 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 21 <init-param> 22 <param-name>encoding</param-name> 23 <param-value>UTF-8</param-value> 24 </init-param> 25 </filter> 26 27 <filter-mapping> 28 <filter-name>encodingFilter</filter-name> 29 <url-pattern>/*</url-pattern> 30 </filter-mapping> 31 32 <listener> 33 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 34 </listener> 35 <!-- spring請求配置,指向springmvc的核心配置文件,定義全部以.do結尾的請求都被springmvc攔截 --> 36 <servlet> 37 <servlet-name>springMVC</servlet-name> 38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 39 <init-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring-context-mvc.xml</param-value> 42 </init-param> 43 <!--加載順序爲1 --> 44 <load-on-startup>1</load-on-startup> 45 </servlet> 46 47 <servlet-mapping> 48 <servlet-name>springMVC</servlet-name> 49 <url-pattern>/</url-pattern> 50 </servlet-mapping> 51 52 <!--錯誤頁面配置,這裏只是簡單的配置了一下 --> 53 <error-page> 54 <error-code>404</error-code> 55 <location>/main.jsp</location> 56 </error-page> 57 58 <error-page> 59 <error-code>500</error-code> 60 <location>/main.jsp</location> 61 </error-page> 62 <!--錯誤頁面配置 --> 63 64 <!--druid監控頁面 --> 65 <servlet> 66 <servlet-name>DruidStatView</servlet-name> 67 <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> 68 <init-param> 69 <!-- 不容許清空統計數據 --> 70 <param-name>resetEnable</param-name> 71 <param-value>false</param-value> 72 </init-param> 73 <init-param> 74 <!-- 用戶名 --> 75 <param-name>loginUsername</param-name> 76 <param-value>yourname</param-value> 77 </init-param> 78 <init-param> 79 <!-- 密碼 --> 80 <param-name>loginPassword</param-name> 81 <param-value>yourpassword</param-value> 82 </init-param> 83 </servlet> 84 <servlet-mapping> 85 <servlet-name>DruidStatView</servlet-name> 86 <url-pattern>/druid/*</url-pattern> 87 </servlet-mapping> 88 <!-- 添加Web應用等監控--> 89 <filter> 90 <filter-name>DruidWebStatFilter</filter-name> 91 <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> 92 <init-param> 93 <param-name>exclusions</param-name> 94 <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> 95 </init-param> 96 <init-param> 97 <param-name>profileEnable</param-name> 98 <param-value>true</param-value> 99 </init-param> 100 <init-param> 101 <param-name>principalCookieName</param-name> 102 <param-value>ssm-admin</param-value> 103 </init-param> 104 <init-param> 105 <param-name>principalSessionName</param-name> 106 <param-value>ssm-admin-session</param-value> 107 </init-param> 108 </filter> 109 <filter-mapping> 110 <filter-name>DruidWebStatFilter</filter-name> 111 <url-pattern>/*</url-pattern> 112 </filter-mapping> 113 <!-- 添加Web應用等監控--> 114 <!--druid監控頁面 --> 115 116 </web-app>
1 # database configure 2 jdbc.url=jdbc:mysql://localhost:3306/ssm-test?useUnicode=true&characterEncoding=utf-8 3 jdbc.username=root 4 jdbc.password=root 5 6 # druid datasource 7 druid.initialSize=10 8 druid.minIdle=10 9 druid.maxActive=50 10 druid.maxWait=60000 11 druid.timeBetweenEvictionRunsMillis=60000 12 druid.minEvictableIdleTimeMillis=300000 13 druid.validationQuery=SELECT 1 14 druid.testWhileIdle=true 15 druid.testOnBorrow=false 16 druid.testOnReturn=false 17 druid.poolPreparedStatements=false 18 druid.maxPoolPreparedStatementPerConnectionSize=20 19 druid.filters=wall,stat
1 #log4j.rootLogger = [level],appenderName,appenderName2,... 2 #level\u662F\u65E5\u5FD7\u8BB0\u5F55\u7684\u4F18\u5148\u7EA7\uFF0C\u5206\u4E3AOFF,TRACE,DEBUG,INFO,WARN,ERROR,FATAL,ALL 3 ##Log4j\u5EFA\u8BAE\u53EA\u4F7F\u7528\u56DB\u4E2A\u7EA7\u522B\uFF0C\u4F18\u5148\u7EA7\u4ECE\u4F4E\u5230\u9AD8\u5206\u522B\u662FDEBUG,INFO,WARN,ERROR 4 #\u901A\u8FC7\u5728\u8FD9\u91CC\u5B9A\u4E49\u7684\u7EA7\u522B\uFF0C\u60A8\u53EF\u4EE5\u63A7\u5236\u5230\u5E94\u7528\u7A0B\u5E8F\u4E2D\u76F8\u5E94\u7EA7\u522B\u7684\u65E5\u5FD7\u4FE1\u606F\u7684\u5F00\u5173 5 #\u6BD4\u5982\u5728\u8FD9\u91CC\u5B9A\u4E49\u4E86INFO\u7EA7\u522B\uFF0C\u5219\u5E94\u7528\u7A0B\u5E8F\u4E2D\u6240\u6709DEBUG\u7EA7\u522B\u7684\u65E5\u5FD7\u4FE1\u606F\u5C06\u4E0D\u88AB\u6253\u5370\u51FA\u6765 6 7 log4j.rootLogger=DEBUG,debug,druid 8 9 #Log4j\u9488\u5BF9\u4E0D\u540C\u5305\u6307\u5B9Alevel\uFF1A 10 #\u4E00\u822C\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u5E94\u7528\u7CFB\u7EDF\uFF0C\u65E5\u5FD7\u7EA7\u522B\u8C03\u6574\u4E3AINFO\u4EE5\u907F\u514D\u8FC7\u591A\u7684\u8F93\u51FA\u65E5\u5FD7\u3002 11 #\u4F46\u67D0\u4E9B\u65F6\u5019\uFF0C\u9700\u8981\u8DDF\u8E2A\u5177\u4F53\u95EE\u9898\uFF0C\u90A3\u4E48\u5C31\u5F97\u6253\u5F00DEBUG\u65E5\u5FD7\u3002 12 #\u4F46\u662F\u5982\u679C\u6253\u5F00log4j.rootLogger\uFF0C\u5219\u9700\u8981\u7684\u4FE1\u606F\u5C31\u4F1A\u6DF9\u6CA1\u5728\u65E5\u5FD7\u7684\u6D77\u6D0B\u4E2D\u3002 13 #\u6B64\u65F6\uFF0C\u9700\u8981\u5355\u72EC\u6307\u5B9A\u67D0\u4E2A\u6216\u8005\u67D0\u4E9BLogger\u7684\u65E5\u5FD7\u7EA7\u522B\u4E3ADEBUG\uFF0C\u800CrootLogger\u4FDD\u6301INFO\u4E0D\u53D8\u3002 14 #\u53C2\u8003\u914D\u7F6E\u5982\u4E0B\uFF08\u6307\u5B9Acom.ssm.maven.core.admin\u7C7B\u7684\u65E5\u5FD7\u8F93\u51FA\uFF09 15 log4j.logger.com.ssm.maven.core.admin=INFO,admin 16 log4j.logger.com.ssm.maven.core.service=INFO,service 17 18 # Druid 19 log4j.logger.druid.sql=WARN,druid 20 log4j.logger.druid.sql.DataSource=WARN,druid 21 log4j.logger.druid.sql.Connection=WARN,druid 22 log4j.logger.druid.sql.Statement=WARN,druid 23 24 log4j.logger.org.springframework=OFF 25 log4j.logger.org.mybatis.spring=ON 26 log4j.logger.org.springframework.context.annotation=OFF 27 28 log4j.appender.druid=org.apache.log4j.DailyRollingFileAppender 29 log4j.appender.druid.layout=org.apache.log4j.PatternLayout 30 log4j.appender.druid.layout.ConversionPattern= [%d{HH\:mm\:ss}] %c{1} - %m%n 31 log4j.appender.druid.datePattern='.'yyyy-MM-dd 32 log4j.appender.druid.Threshold = WARN 33 log4j.appender.druid.append=true 34 log4j.appender.druid.File=${catalina.home}/logs/ssm-maven/druid-slow-sql.log 35 36 log4j.appender.admin=org.apache.log4j.DailyRollingFileAppender 37 log4j.appender.admin.layout=org.apache.log4j.PatternLayout 38 log4j.appender.admin.layout.ConversionPattern= [%d{HH\:mm\:ss}] %c{1} - %m%n 39 log4j.appender.admin.datePattern='.'yyyy-MM-dd 40 log4j.appender.admin.Threshold = INFO 41 log4j.appender.admin.append=true 42 log4j.appender.admin.File=${catalina.home}/logs/ssm-maven/admin.log 43 44 log4j.appender.service=org.apache.log4j.DailyRollingFileAppender 45 log4j.appender.service.layout=org.apache.log4j.PatternLayout 46 log4j.appender.service.layout.ConversionPattern= [%d{HH\:mm\:ss}] %c{1} - %m%n 47 log4j.appender.service.datePattern='.'yyyy-MM-dd 48 log4j.appender.service.Threshold = INFO 49 log4j.appender.service.append=true 50 log4j.appender.service.File=${catalina.home}/logs/ssm-maven/service.log 51 52 log4j.logger.debug=debug 53 log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender 54 log4j.appender.debug.layout=org.apache.log4j.PatternLayout 55 log4j.appender.debug.layout.ConversionPattern= [%d{HH\:mm\:ss}] %c{1} - %m%n 56 log4j.appender.debug.datePattern='.'yyyy-MM-dd 57 log4j.appender.debug.Threshold = DEBUG 58 log4j.appender.debug.append=true 59 log4j.appender.debug.File=${catalina.home}/logs/ssm-maven/debug.log 60 61 log4j.logger.java.sql.ResultSet=INFO 62 log4j.logger.org.apache=INFO 63 log4j.logger.java.sql.Connection=DEBUG 64 log4j.logger.java.sql.Statement=DEBUG 65 log4j.logger.java.sql.PreparedStatement=DEBUG
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!-- 別名 --> 7 <settings> 8 <setting name="logImpl" value="LOG4J"/> 9 </settings> 10 <typeAliases> 11 <package name="com.cn.hnust.pojo"/> 12 </typeAliases> 13 </configuration>
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:aop="http://www.springframework.org/schema/aop" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 6 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 7 8 <!-- 監控spring的切面,若是不想監控,將此文件刪除便可--> 9 <bean id="druid-stat-interceptor" 10 class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> 11 </bean> 12 13 <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" 14 scope="prototype"> 15 <property name="patterns"> 16 <list> 17 <value>com.cn.hnust.service.*</value> 18 <value>com.cn.hnust.dao.*</value> 19 </list> 20 </property> 21 </bean> 22 23 <aop:config> 24 <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut"/> 25 </aop:config> 26 27 </beans>
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:p="http://www.springframework.org/schema/p" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc 9 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 10 11 <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 --> 12 <context:component-scan base-package="com.cn.hnust.controller" /> 13 14 <!-- 視圖解析器 --> 15 <bean id="viewResolver" 16 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 17 <property name="prefix" value="/WEB-INF/jsp/" /> 18 <property name="suffix" value=".jsp"></property> 19 </bean> 20 21 <bean id="multipartResolver" 22 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 23 <property name="maxUploadSize" value="3500000" /> 24 <property name="defaultEncoding" value="UTF-8" /> 25 </bean> 26 27 <!-- Start: 配置json消息轉換器 & 參數解析 --> 28 <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"> 29 <property name="dateFormat"> 30 <bean class="java.text.SimpleDateFormat"> 31 <constructor-arg index="0" type="java.lang.String" 32 value="yyyy-MM-dd HH:mm:ss" /> 33 </bean> 34 </property> 35 </bean> 36 <mvc:annotation-driven> 37 <mvc:message-converters register-defaults="true"> 38 <bean 39 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 40 <property name="supportedMediaTypes"> 41 <list> 42 <value>application/json; charset=UTF-8</value> 43 </list> 44 </property> 45 <property name="prettyPrint" value="true" /> 46 <property name="objectMapper" ref="objectMapper" /> 47 </bean> 48 </mvc:message-converters> 49 </mvc:annotation-driven> 50 <!-- End: 配置json消息轉換器 & 參數解析 --> 51 52 <!-- 使用了<url-pattern>/</url-pattern>,因此要對靜態資源進行處理 --> 53 <mvc:default-servlet-handler /> 54 55 </beans>
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 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 7 <property name="locations"> 8 <list> 9 <value>classpath*:/jdbc-druid-config.properties</value> 10 </list> 11 </property> 12 </bean> 13 14 <!-- 配置mybatis的sqlSessionFactory --> 15 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 16 <property name="dataSource" ref="dataSource"/> 17 </bean> 18 19 <!-- DAO接口所在包名,Spring會自動查找其下的類 --> 20 <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"> 21 <property name="basePackage" value="com.cn.hnust.dao" /> 22 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 23 </bean> 24 25 <!-- 數據源 --> 26 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 27 <!-- 基本屬性 url、user、password --> 28 <property name="url" value="${jdbc.url}"/> 29 <property name="username" value="${jdbc.username}"/> 30 <property name="password" value="${jdbc.password}"/> 31 32 <!-- 配置初始化大小、最小、最大 --> 33 <property name="initialSize" value="${druid.initialSize}"/> 34 <property name="minIdle" value="${druid.minIdle}"/> 35 <property name="maxActive" value="${druid.maxActive}"/> 36 37 <!-- 配置獲取鏈接等待超時的時間 --> 38 <property name="maxWait" value="${druid.maxWait}"/> 39 <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> 40 <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/> 41 42 <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> 43 <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/> 44 45 <property name="validationQuery" value="${druid.validationQuery}"/> 46 <property name="testWhileIdle" value="${druid.testWhileIdle}"/> 47 <property name="testOnBorrow" value="${druid.testOnBorrow}"/> 48 <property name="testOnReturn" value="${druid.testOnReturn}"/> 49 50 <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 若是用Oracle,則把poolPreparedStatements配置爲true,mysql能夠配置爲false。--> 51 <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}"/> 52 <property name="maxPoolPreparedStatementPerConnectionSize" 53 value="${druid.maxPoolPreparedStatementPerConnectionSize}"/> 54 55 <!-- 配置監控統計攔截的filters --> 56 <property name="filters" value="${druid.filters}"/> 57 58 <!--Start 慢sql監控及log4j設置--> 59 <property name="proxyFilters"> 60 <list> 61 <ref bean="stat-filter"/> 62 <ref bean="log-filter"/> 63 </list> 64 </property> 65 <!--End 慢sql監控及log4j設置,不想監控的話將proxyFilters屬性刪除便可 --> 66 67 </bean> 68 69 <!-- 慢SQL記錄 --> 70 <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter"> 71 <property name="mergeSql" value="true"/> 72 <!-- 慢sql時間設置,即執行時間大於200毫秒的都是慢sql --> 73 <property name="slowSqlMillis" value="200"/> 74 <property name="logSlowSql" value="true"/> 75 </bean> 76 77 <bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter"> 78 <property name="dataSourceLogEnabled" value="true" /> 79 <property name="statementExecutableSqlLogEnable" value="true" /> 80 </bean> 81 82 </beans>
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:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 8 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 9 10 <!-- mybatis及數據源配置 --> 11 <import resource="classpath:spring-context-mybatis.xml"/> 12 13 <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> 14 <bean id="transactionManager" 15 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 16 <property name="dataSource" ref="dataSource"/> 17 </bean> 18 19 <!-- 配置事務通知屬性 --> 20 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 21 <!-- 定義事務傳播屬性 --> 22 <tx:attributes> 23 <tx:method name="insert*" propagation="REQUIRED"/> 24 <tx:method name="update*" propagation="REQUIRED"/> 25 <tx:method name="upd*" propagation="REQUIRED"/> 26 <tx:method name="edit*" propagation="REQUIRED"/> 27 <tx:method name="save*" propagation="REQUIRED"/> 28 <tx:method name="add*" propagation="REQUIRED"/> 29 <tx:method name="new*" propagation="REQUIRED"/> 30 <tx:method name="set*" propagation="REQUIRED"/> 31 <tx:method name="remove*" propagation="REQUIRED"/> 32 <tx:method name="delete*" propagation="REQUIRED"/> 33 <tx:method name="del*" propagation="REQUIRED"/> 34 <tx:method name="change*" propagation="REQUIRED"/> 35 <tx:method name="check*" propagation="REQUIRED"/> 36 <tx:method name="get*" propagation="REQUIRED" read-only="true"/> 37 <tx:method name="search*" propagation="REQUIRED" read-only="true"/> 38 <tx:method name="find*" propagation="REQUIRED" read-only="true"/> 39 <tx:method name="load*" propagation="REQUIRED" read-only="true"/> 40 <tx:method name="*" propagation="REQUIRED" read-only="true"/> 41 </tx:attributes> 42 </tx:advice> 43 44 <!-- 配置事務切面 --> 45 <aop:config> 46 <aop:pointcut id="serviceOperation" 47 expression="(execution(* com.cn.hnust.service.*.*(..)))"/> 48 <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/> 49 </aop:config> 50 51 </beans>
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 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 7 8 <!-- 自動掃描 --> 9 <context:component-scan base-package="com.cn.hnust.dao"/> 10 <context:component-scan base-package="com.cn.hnust.service"/> 11 12 <!-- druid監控配置 --> 13 <import resource="classpath:spring-context-druid-stat.xml"/> 14 <!-- 事務管理配置 --> 15 <import resource="classpath:spring-context-tx.xml"/> 16 17 </beans>
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.ssm.maven.core</groupId> 5 <artifactId>ssm-maven</artifactId> 6 <packaging>war</packaging> 7 <version>1.0-SNAPSHOT</version> 8 <name>ssm-maven</name> 9 <url>http://maven.apache.org</url> 10 11 <properties> 12 <!-- spring版本號 --> 13 <spring.version>4.0.2.RELEASE</spring.version> 14 <!-- mybatis版本號 --> 15 <mybatis.version>3.2.6</mybatis.version> 16 <!-- log4j日誌文件管理包版本 --> 17 <slf4j.version>1.7.7</slf4j.version> 18 <log4j.version>1.2.17</log4j.version> 19 </properties> 20 21 <dependencies> 22 <dependency> 23 <groupId>junit</groupId> 24 <artifactId>junit</artifactId> 25 <version>4.11</version> 26 <!-- 表示開發的時候引入,發佈的時候不會加載此包 --> 27 <scope>test</scope> 28 </dependency> 29 <!-- spring核心包 --> 30 <dependency> 31 <groupId>org.springframework</groupId> 32 <artifactId>spring-core</artifactId> 33 <version>${spring.version}</version> 34 </dependency> 35 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-web</artifactId> 39 <version>${spring.version}</version> 40 </dependency> 41 <dependency> 42 <groupId>org.springframework</groupId> 43 <artifactId>spring-oxm</artifactId> 44 <version>${spring.version}</version> 45 </dependency> 46 <dependency> 47 <groupId>org.springframework</groupId> 48 <artifactId>spring-tx</artifactId> 49 <version>${spring.version}</version> 50 </dependency> 51 52 <dependency> 53 <groupId>org.springframework</groupId> 54 <artifactId>spring-jdbc</artifactId> 55 <version>${spring.version}</version> 56 </dependency> 57 58 <dependency> 59 <groupId>org.springframework</groupId> 60 <artifactId>spring-webmvc</artifactId> 61 <version>${spring.version}</version> 62 </dependency> 63 <dependency> 64 <groupId>org.springframework</groupId> 65 <artifactId>spring-aop</artifactId> 66 <version>${spring.version}</version> 67 </dependency> 68 69 <dependency> 70 <groupId>org.springframework</groupId> 71 <artifactId>spring-context-support</artifactId> 72 <version>${spring.version}</version> 73 </dependency> 74 75 <dependency> 76 <groupId>org.springframework</groupId> 77 <artifactId>spring-test</artifactId> 78 <version>${spring.version}</version> 79 </dependency> 80 <!-- mybatis核心包 --> 81 <dependency> 82 <groupId>org.mybatis</groupId> 83 <artifactId>mybatis</artifactId> 84 <version>${mybatis.version}</version> 85 </dependency> 86 <!-- mybatis/spring包 --> 87 <dependency> 88 <groupId>org.mybatis</groupId> 89 <artifactId>mybatis-spring</artifactId> 90 <version>1.2.2</version> 91 </dependency> 92 <dependency> 93 <groupId>tk.mybatis</groupId> 94 <artifactId>mapper</artifactId> 95 <version>3.3.7</version> 96 </dependency> 97 <dependency> 98 <groupId>javax.persistence</groupId> 99 <artifactId>persistence-api</artifactId> 100 <version>1.0</version> 101 </dependency> 102 <!-- 導入java ee jar 包 --> 103 <dependency> 104 <groupId>javax</groupId> 105 <artifactId>javaee-api</artifactId> 106 <version>7.0</version> 107 </dependency> 108 <!-- 導入Mysql數據庫連接jar包 --> 109 <dependency> 110 <groupId>mysql</groupId> 111 <artifactId>mysql-connector-java</artifactId> 112 <version>5.1.30</version> 113 </dependency> 114 <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 --> 115 <dependency> 116 <groupId>commons-dbcp</groupId> 117 <artifactId>commons-dbcp</artifactId> 118 <version>1.2.2</version> 119 </dependency> 120 <!-- JSTL標籤類 --> 121 <dependency> 122 <groupId>jstl</groupId> 123 <artifactId>jstl</artifactId> 124 <version>1.2</version> 125 </dependency> 126 <!-- 日誌文件管理包 --> 127 <!-- log start --> 128 <dependency> 129 <groupId>log4j</groupId> 130 <artifactId>log4j</artifactId> 131 <version>${log4j.version}</version> 132 </dependency> 133 134 135 <!-- 格式化對象,方便輸出日誌 --> 136 <dependency> 137 <groupId>com.alibaba</groupId> 138 <artifactId>fastjson</artifactId> 139 <version>1.1.41</version> 140 </dependency> 141 142 143 <dependency> 144 <groupId>org.slf4j</groupId> 145 <artifactId>slf4j-api</artifactId> 146 <version>${slf4j.version}</version> 147 </dependency> 148 149 <dependency> 150 <groupId>org.slf4j</groupId> 151 <artifactId>slf4j-log4j12</artifactId> 152 <version>${slf4j.version}</version> 153 </dependency> 154 <!-- log end --> 155 <!-- 映入JSON --> 156 <dependency> 157 <groupId>org.codehaus.jackson</groupId> 158 <artifactId>jackson-mapper-asl</artifactId> 159 <version>1.9.13</version> 160 </dependency> 161 <dependency> 162 <groupId>com.fasterxml.jackson.core</groupId> 163 <artifactId>jackson-databind</artifactId> 164 <version>2.5.3</version> 165 </dependency> 166 <!-- 上傳組件包 --> 167 <dependency> 168 <groupId>commons-fileupload</groupId> 169 <artifactId>commons-fileupload</artifactId> 170 <version>1.3.1</version> 171 </dependency> 172 <dependency> 173 <groupId>commons-io</groupId> 174 <artifactId>commons-io</artifactId> 175 <version>2.4</version> 176 </dependency> 177 <dependency> 178 <groupId>commons-codec</groupId> 179 <artifactId>commons-codec</artifactId> 180 <version>1.9</version> 181 </dependency> 182 <!-- Start: druid --> 183 <dependency> 184 <groupId>com.alibaba</groupId> 185 <artifactId>druid</artifactId> 186 <!-- 版本號你本身選 --> 187 <version>1.0.24</version> 188 </dependency> 189 <!-- End: druid --> 190 <!-- Begin: aspectj相關jar包--> 191 <dependency> 192 <groupId>org.aspectj</groupId> 193 <artifactId>aspectjrt</artifactId> 194 <version>1.7.4</version> 195 </dependency> 196 <dependency> 197 <groupId>org.aspectj</groupId> 198 <artifactId>aspectjweaver</artifactId> 199 <version>1.7.4</version> 200 </dependency> 201 <!-- End: aspectj相關jar包--> 202 </dependencies> 203 </project>
1 package com.cn.hnust.common; 2 3 public class Constants { 4 public static final int RESULT_CODE_SUCCESS = 200; // 成功處理請求 5 public static final int RESULT_CODE_BAD_REQUEST = 412; // bad request 6 public static final int RESULT_CODE_SERVER_ERROR = 500; // 沒有對應結果 7 8 public static final String ARTICLE_CACHE_KEY = "perfect-ssm:article:";//文章key 9 public static final String PICTURE_CACHE_KEY = "perfect-ssm:picture:";//圖片key 10 }
1 package com.cn.hnust.common; 2 3 import java.io.Serializable; 4 5 public class Result<T> implements Serializable { 6 private static final long serialVersionUID = 1L; 7 private int resultCode; 8 private String message; 9 private T data; 10 11 public Result() { 12 } 13 14 public Result(int resultCode, String message) { 15 this.resultCode = resultCode; 16 this.message = message; 17 } 18 19 public int getResultCode() { 20 return resultCode; 21 } 22 23 public void setResultCode(int resultCode) { 24 this.resultCode = resultCode; 25 } 26 27 public String getMessage() { 28 return message; 29 } 30 31 public void setMessage(String message) { 32 this.message = message; 33 } 34 35 public T getData() { 36 return data; 37 } 38 39 public void setData(T data) { 40 this.data = data; 41 } 42 43 @Override 44 public String toString() { 45 return "Result{" + 46 "resultCode=" + resultCode + 47 ", message='" + message + '\'' + 48 ", data={" + data.toString() + "}" + 49 '}'; 50 } 51 52 }
1 package com.cn.hnust.common; 2 3 public class ResultGenerator { 4 private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; 5 private static final String DEFAULT_FAIL_MESSAGE = "FAIL"; 6 7 public static Result genSuccessResult() { 8 Result result = new Result(); 9 result.setResultCode(Constants.RESULT_CODE_SUCCESS); 10 result.setMessage(DEFAULT_SUCCESS_MESSAGE); 11 return result; 12 } 13 14 public static Result genSuccessResult(Object data) { 15 Result result = new Result(); 16 result.setResultCode(Constants.RESULT_CODE_SUCCESS); 17 result.setMessage(DEFAULT_SUCCESS_MESSAGE); 18 result.setData(data); 19 return result; 20 } 21 22 public static Result genFailResult(String message) { 23 Result result = new Result(); 24 result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR); 25 if (message == null || message.length() < 1) { 26 message = DEFAULT_FAIL_MESSAGE; 27 } 28 result.setMessage(message); 29 return result; 30 } 31 32 }
1 package com.cn.hnust.controller; 2 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.annotation.Resource; 8 9 import org.apache.log4j.Logger; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.web.bind.annotation.PathVariable; 12 import org.springframework.web.bind.annotation.RequestBody; 13 import org.springframework.web.bind.annotation.RequestMapping; 14 import org.springframework.web.bind.annotation.RequestMethod; 15 import org.springframework.web.bind.annotation.RequestParam; 16 import org.springframework.web.bind.annotation.ResponseBody; 17 18 import com.cn.hnust.common.Result; 19 import com.cn.hnust.common.ResultGenerator; 20 import com.cn.hnust.pojo.PageBean; 21 import com.cn.hnust.pojo.User; 22 import com.cn.hnust.service.IUserService; 23 import com.cn.hnust.util.MD5Util; 24 25 @Controller 26 @RequestMapping("/user") 27 public class UserController { 28 @Resource 29 private IUserService userService; 30 31 private static final Logger log = Logger.getLogger(UserController.class);// 日誌文件 32 33 /** 34 * 查詢id 35 * @param id 36 * @return 37 * @throws Exception 38 */ 39 @RequestMapping(value = "/{id}", method = RequestMethod.GET) 40 @ResponseBody 41 public Result findById(@PathVariable("id") String id) throws Exception { 42 User user = this.userService.getUserById(Integer.parseInt(id)); 43 log.info("request: user/findById"); 44 if (user != null) { 45 Result result = ResultGenerator.genSuccessResult(); 46 result.setData(user); 47 return result; 48 } else { 49 return ResultGenerator.genFailResult("無數據"); 50 } 51 } 52 53 /** 54 * 列表 55 * @param page 56 * @param rows 57 * @param user 58 * @return 59 * @throws Exception 60 */ 61 @RequestMapping(value = "", method = RequestMethod.GET) 62 @ResponseBody 63 public Result list( 64 @RequestParam(value = "page", required = false) String page, 65 @RequestParam(value = "rows", required = false) String rows, 66 User user) throws Exception { 67 Map<String, Object> map = new HashMap<String, Object>(); 68 if (page != null && rows != null) { 69 PageBean pageBean = new PageBean(Integer.parseInt(page), 70 Integer.parseInt(rows)); 71 map.put("start", pageBean.getStart()); 72 map.put("size", pageBean.getPageSize()); 73 } 74 if (user.getUserName() != null) { 75 map.put("name", user.getUserName()); 76 } 77 List<User> list = this.userService.findUser(map); 78 Result result = ResultGenerator.genSuccessResult(); 79 Long total = this.userService.getTotalUser(map); 80 Map data = new HashMap(); 81 data.put("rows", list); 82 data.put("total", total); 83 log.info("request: user/list , map: " + map.toString()); 84 result.setData(data); 85 return result; 86 } 87 88 /** 89 * 添加 90 * 91 * @return 92 * @throws Exception 93 */ 94 @RequestMapping(value = "", method = RequestMethod.POST) 95 @ResponseBody 96 public Result save(@RequestBody User user) throws Exception { 97 int resultTotal = 0; 98 String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8"); 99 user.setPassword(MD5pwd); 100 resultTotal = userService.addUser(user); 101 if (resultTotal > 0) { 102 return ResultGenerator.genSuccessResult(); 103 } else { 104 return ResultGenerator.genFailResult("FAIL"); 105 } 106 } 107 108 /** 109 * 修改所有屬性 110 * 111 * @param user 112 * @return 113 * @throws Exception 114 */ 115 @RequestMapping(value = "", method = RequestMethod.PUT) 116 @ResponseBody 117 public Result update(@RequestBody User user) throws Exception { 118 String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8"); 119 user.setPassword(MD5pwd); 120 int resultTotal = userService.updateUserAll(user); 121 log.info("request: user/update , user: " + user.toString()); 122 if (resultTotal > 0) { 123 return ResultGenerator.genSuccessResult(); 124 } else { 125 return ResultGenerator.genFailResult("FAIL"); 126 } 127 } 128 129 /** 130 * 修改部分屬性 131 * 132 * @param user 133 * @return 134 * @throws Exception 135 */ 136 @RequestMapping(value = "", method = RequestMethod.PATCH) 137 @ResponseBody 138 public Result update1(@RequestBody User user) throws Exception { 139 String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8"); 140 user.setPassword(MD5pwd); 141 int resultTotal = userService.updateUser(user); 142 log.info("request: user/update , user: " + user.toString()); 143 if (resultTotal > 0) { 144 return ResultGenerator.genSuccessResult(); 145 } else { 146 return ResultGenerator.genFailResult("FAIL"); 147 } 148 } 149 150 /** 151 * 刪除管理員 152 * 153 * @param ids 154 * @return 155 * @throws Exception 156 */ 157 @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE) 158 @ResponseBody 159 public Result delete(@PathVariable(value = "ids") String ids) throws Exception { 160 if (ids.length() > 20) { 161 return ResultGenerator.genFailResult("ERROR"); 162 } 163 String[] idsStr = ids.split(","); 164 for (int i = 0; i < idsStr.length; i++) { 165 userService.deleteUser(Integer.valueOf(idsStr[i])); 166 } 167 log.info("request: article/delete , ids: " + ids); 168 return ResultGenerator.genSuccessResult(); 169 } 170 }
1 package com.cn.hnust.dao; 2 3 import com.cn.hnust.pojo.User; 4 5 import tk.mybatis.mapper.common.Mapper; 6 7 public interface IUserDao extends Mapper<User> { 8 9 }
1 package com.cn.hnust.pojo; 2 3 public class PageBean { 4 5 private int page; // 頁碼 6 private int pageSize; // 單頁數據量 7 private int start; 8 9 10 public PageBean(int page, int pageSize) { 11 super(); 12 this.page = page; 13 this.pageSize = pageSize; 14 } 15 16 public int getPage() { 17 return page; 18 } 19 20 public void setPage(int page) { 21 this.page = page; 22 } 23 24 public int getPageSize() { 25 return pageSize; 26 } 27 28 public void setPageSize(int pageSize) { 29 this.pageSize = pageSize; 30 } 31 32 public int getStart() { 33 return (page - 1) * pageSize; 34 } 35 }
1 package com.cn.hnust.pojo; 2 3 import javax.persistence.Column; 4 import javax.persistence.Id; 5 import javax.persistence.Table; 6 7 @Table(name = "user_t") 8 public class User { 9 10 @Id 11 private Integer id; 12 13 @Column 14 private String userName; 15 16 @Column 17 private String password; 18 19 @Column 20 private Integer age; 21 22 public Integer getId() { 23 return id; 24 } 25 26 public void setId(Integer id) { 27 this.id = id; 28 } 29 30 public String getUserName() { 31 return userName; 32 } 33 34 public void setUserName(String userName) { 35 this.userName = userName == null ? null : userName.trim(); 36 } 37 38 public String getPassword() { 39 return password; 40 } 41 42 public void setPassword(String password) { 43 this.password = password == null ? null : password.trim(); 44 } 45 46 public Integer getAge() { 47 return age; 48 } 49 50 public void setAge(Integer age) { 51 this.age = age; 52 } 53 }
1 package com.cn.hnust.service; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import com.cn.hnust.pojo.User; 7 8 public interface IUserService { 9 public User getUserById(int userId); 10 11 public List<User> getUserByName(String name); 12 13 public List<User> findUser(Map<String, Object> map); 14 15 public Long getTotalUser(Map<String, Object> map); 16 17 public int updateUserAll(User user); 18 19 public int updateUser(User user); 20 21 public int addUser(User user); 22 23 public int deleteUser(Integer id); 24 }
1 package com.cn.hnust.service.impl; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import javax.annotation.Resource; 7 8 import org.springframework.stereotype.Service; 9 10 import com.cn.hnust.dao.IUserDao; 11 import com.cn.hnust.pojo.User; 12 import com.cn.hnust.service.IUserService; 13 import com.mysql.jdbc.StringUtils; 14 15 import tk.mybatis.mapper.entity.Example; 16 import tk.mybatis.mapper.util.StringUtil; 17 18 @Service("userService") 19 public class UserServiceImpl implements IUserService { 20 21 @Resource 22 private IUserDao userDao; 23 24 @Override 25 public User getUserById(int userId) { 26 // TODO Auto-generated method stub 27 return this.userDao.selectByPrimaryKey(userId); 28 } 29 30 @Override 31 public List<User> getUserByName(String name){ 32 Example example = new Example(User.class); 33 example.setOrderByClause("id"); 34 Example.Criteria criteria = example.createCriteria(); 35 criteria.andLike("userName", "%" + name + "%"); 36 //criteria.andEqualTo("xm", "xm"); 37 criteria.andGreaterThan("age", "23"); 38 criteria.andIsNotNull("userName"); 39 //criteria.andCondition("xzdqh=","110104"); 40 //criteria.andIn("xzdqh", new ArrayList<String>()); 41 //criteria.andBetween("csrq", "1956/01/08", "1966/10/21"); 42 //Example.Criteria criteria2 = example.createCriteria(); 43 //example.or().andCondition("xzdqh=","220104"); 44 //example.or(criteria2); 45 return this.userDao.selectByExample(example); 46 } 47 48 49 @Override 50 public List<User> findUser(Map<String, Object> map) { 51 Example example = new Example(User.class); 52 example.setOrderByClause("id"); 53 Example.Criteria criteria = example.createCriteria(); 54 if(map.get("name")!=null && !StringUtils.isNullOrEmpty(map.get("name").toString())){ 55 criteria.andLike("userName", "%" + map.get("name").toString() + "%"); 56 } 57 if(map.get("start")!=null && map.get("size")!=null && (int)map.get("size")!=0){ 58 criteria.andCondition("limit " + map.get("start") + "," + map.get("size")); 59 } 60 61 return this.userDao.selectByExample(example); 62 } 63 64 @Override 65 public Long getTotalUser(Map<String, Object> map) { 66 Example example = new Example(User.class); 67 Example.Criteria criteria = example.createCriteria(); 68 if(map.get("name")!=null && !StringUtils.isNullOrEmpty(map.get("name").toString())){ 69 criteria.andLike("userName", "%" + map.get("name").toString() + "%"); 70 } 71 if(map.get("start")!=null && map.get("size")!=null && (int)map.get("size")!=0){ 72 criteria.andCondition("limit " + map.get("start") + "," + map.get("size")); 73 } 74 75 return (long)this.userDao.selectCountByExample(example); 76 } 77 78 @Override 79 public int updateUserAll(User user) { 80 return userDao.updateByPrimaryKey(user); 81 } 82 83 @Override 84 public int updateUser(User user) { 85 return userDao.updateByPrimaryKeySelective(user); 86 } 87 88 @Override 89 public int addUser(User user) { 90 return userDao.insert(user); 91 } 92 93 @Override 94 public int deleteUser(Integer id) { 95 Example example = new Example(User.class); 96 Example.Criteria criteria = example.createCriteria(); 97 criteria.andEqualTo("id", id); 98 return userDao.deleteByExample(example); 99 } 100 101 }
1 package com.cn.hnust.util; 2 3 import java.security.MessageDigest; 4 5 public class MD5Util { 6 private static String byteArrayToHexString(byte b[]) { 7 StringBuffer resultSb = new StringBuffer(); 8 for (int i = 0; i < b.length; i++) 9 resultSb.append(byteToHexString(b[i])); 10 11 return resultSb.toString(); 12 } 13 14 private static String byteToHexString(byte b) { 15 int n = b; 16 if (n < 0) 17 n += 256; 18 int d1 = n / 16; 19 int d2 = n % 16; 20 return hexDigits[d1] + hexDigits[d2]; 21 } 22 23 public static String MD5Encode(String origin, String charsetname) { 24 String resultString = null; 25 try { 26 resultString = new String(origin); 27 MessageDigest md = MessageDigest.getInstance("MD5"); 28 if (charsetname == null || "".equals(charsetname)) 29 resultString = byteArrayToHexString(md.digest(resultString 30 .getBytes())); 31 else 32 resultString = byteArrayToHexString(md.digest(resultString 33 .getBytes(charsetname))); 34 } catch (Exception exception) { 35 } 36 return resultString; 37 } 38 39 private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", 40 "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; 41 }
1 [POST] localhost:8080/ssm-maven/user // 新增 2 [GET] localhost:8080/ssm-maven/user?page=1&rows=10 // 列表查詢 3 [PUT] localhost:8080/ssm-maven/user // 修改 4 [DELETE] localhost:8080/ssm-maven/user/1 // 刪除 5 [GET] localhost:8080/ssm-maven/user/1 //查詢id