1./pom.xml文件内容:
<project xmlns="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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMavenStudy</groupId> <artifactId>SpringMavenStudy</artifactId> <name>SpringMavenStudy</name> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <!-- jdk版本号 --> <jdk.version>1.7</jdk.version> <!-- spring版本号 --> <spring.version>4.2.5.RELEASE</spring.version> <!-- <spring.version>3.2.16.RELEASE</spring.version> --> <!-- mybatis版本号 --> <mybatis.version>3.3.1</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- 支持servlet的jar包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- spring jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- <dependency> --> <!-- <groupId>org.springframework</groupId> --> <!-- <artifactId>spring-aspects</artifactId> --> <!-- <version>${spring.version}</version> --> <!-- </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <!-- <dependency> --> <!-- <groupId>org.springframework</groupId> --> <!-- <artifactId>spring-mock</artifactId> --> <!-- <version>2.0.8</version> --> <!-- <scope>test</scope> --> <!-- </dependency> --> <!-- <dependency> --> <!-- <groupId>org.springframework</groupId> --> <!-- <artifactId>spring-oxm</artifactId> --> <!-- <version>${spring.version}</version> --> <!-- </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- spring-remoting包含支持EJB、JMS、远程调用Remoting(RMI、Hessian、Burlap、Http Invoker、JAX-RPC)方面的类 --> <!-- <dependency> --> <!-- <groupId>org.springframework</groupId> --> <!-- <artifactId>spring-remoting</artifactId> --> <!-- <version>${spring.version}</version> --> <!-- </dependency> --> <!-- spring-support包含支持缓存Cache(ehcache)、JCA、JMX、邮件服务(Java Mail、COS Mail)、任务计划Scheduling(Timer、Quartz)方面的类 --> <!-- <dependency> --> <!-- <groupId>org.springframework</groupId> --> <!-- <artifactId>spring-support</artifactId> --> <!-- <version>${spring.version}</version> --> <!-- </dependency> --> <!-- spring mvc jar --> <!-- 包含Web应用开发时,用到Spring框架时所需的核心类,包括自动载入WebApplicationContext特性的类、Struts与JSF集成类、文件上传的支持类、Filter类和大量工具辅助类 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- webmvc包含国际化、标签、Theme、视图展现FreeMarker、JasperReports、Tiles、Velocity、 XSLT相关类 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> <!-- <type>jar</type> --> <!-- <scope>compile</scope> --> </dependency> <!-- mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> <!-- <type>jar</type> --> <!-- <scope>compile</scope> --> </dependency> <!-- json转换 ,springmvc 返回json格式必须加入 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 集成redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.4.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <!-- freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <!-- excel报表文件处理 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <!-- 支持xlsx格式的excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- BeanUtils主要提供对JavaBean进行各种操作,提供对Java反射和自省API的包装,Spring的AOP用到 --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency> <!-- Digester基于规则的XML文档解析,主要用于XML到Java对象的映射. --> <dependency> <groupId>commons-digester</groupId> <artifactId>commons-digester</artifactId> <version>2.0</version> </dependency> <!-- AspectJ使用Java的注解,将切面AOP声明为普通的Java类 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.9</version> </dependency> <!-- aspectjweaver用于在Spring中集成AspectJ LTW织入器 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <!-- cglib代理 实现AOP的一种方式 ,和它对应的是DynaProxy(java动态代理) --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2</version> </dependency> <!-- 导入java ee jar 包 --> <!-- <dependency> --> <!-- <groupId>javax</groupId> --> <!-- <artifactId>javaee-api</artifactId> --> <!-- <version>7.0</version> --> <!-- </dependency> --> <!--sqlserver驱动包 --> <!-- <dependency> --> <!-- <groupId>com.microsoft.sqlserver</groupId> --> <!-- <artifactId>sqljdbc4</artifactId> --> <!-- <version>3.0</version> --> <!-- </dependency> --> <!-- 导入Mysql数据库驱动jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- 导入sqlite数据库驱动jar包 --> <!-- <dependency> --> <!-- <groupId>org.xerial</groupId> --> <!-- <artifactId>sqlite-jdbc</artifactId> --> <!-- <version>3.8.11.2</version> --> <!-- </dependency> --> <!-- 用于dbcp配置的数据库连接池 --> <!-- <dependency> --> <!-- <groupId>commons-dbcp</groupId> --> <!-- <artifactId>commons-dbcp</artifactId> --> <!-- <version>1.4</version> --> <!-- </dependency> --> <!-- <dependency> --> <!-- <groupId>org.apache.commons</groupId> --> <!-- <artifactId>commons-dbcp2</artifactId> --> <!-- <version>2.1.1</version> --> <!-- </dependency> --> <!-- <dependency> --> <!-- <groupId>commons-pool</groupId> --> <!-- <artifactId>commons-pool</artifactId> --> <!-- <version>1.6</version> --> <!-- </dependency> --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <!-- 用于c3p0配置的数据库连接池--> <!-- <dependency> --> <!-- <groupId>com.mchange</groupId> --> <!-- <artifactId>c3p0</artifactId> --> <!-- <version>0.9.5.2</version> --> <!-- </dependency> --> <!-- 用于Tomcat jdbc配置的数据库连接池 --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>8.0.32</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency> <!-- JSTL标签类 --> <!-- <dependency> --> <!-- <groupId>jstl</groupId> --> <!-- <artifactId>jstl</artifactId> --> <!-- <version>1.2</version> --> <!-- </dependency> --> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- Commons Configuration是一个java应用程序的配置管理工具,可以从properties或者xml文件中加载软件的配置信息,用来构建支撑软件运行的基础环境。在一些配置文件较多较的复杂的情况下,使用该配置工具比较可以简化配置文件的解析和管理。 --> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.6</version> </dependency> <!-- commons-lang包含了一些数据类型工具类,是java.lang.*的扩展,必须使用的jar包。 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- commons-httpclient是一个遗留版本,现在官方已经不推荐使用了。https站点中需要加载SSLContext的类。httpclient是官方现在还在开发的,还在维护的,功能也比较强大的组件,提供更好的性能和更大的灵活性。 --> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.6.0</version> </dependency> <!-- 定时调度 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> </dependencies> <!-- 配置文件 --> <profiles> <!-- <profile> --> <!-- <id>dev</id> --> <!-- <properties> --> <!-- <package.environment>dev</package.environment> --> <!-- </properties> --> <!-- <activation> --> <!-- <activeByDefault>true</activeByDefault> --> <!-- </activation> --> <!-- <build> --> <!-- <resources> --> <!-- <resource> --> <!-- <directory>src/main/config</directory> --> <!-- </resource> --> <!-- </resources> --> <!-- </build> --> <!-- </profile> --> <!-- <profile> --> <!-- <id>test</id> --> <!-- <properties> --> <!-- <package.environment>test</package.environment> --> <!-- </properties> --> <!-- <build> --> <!-- <resources> --> <!-- <resource> --> <!-- <directory>src/main/testConfig</directory> --> <!-- </resource> --> <!-- </resources> --> <!-- </build> --> <!-- </profile> --> </profiles> <!-- 打包部署 --> <build> <finalName>SpringMavenStudy</finalName> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>nexus</id> <name>nexus</name> <url>http://maven.oschina.net/content/groups/public</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus</id> <name>nexus</name> <url>http://maven.oschina.net/content/groups/public</url> </pluginRepository> </pluginRepositories> </project> 2./src/main/webapp/WEB-INF/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>SpringMavenStudy</display-name> <!-- 设置由Sprng载入的Log4j配置文件位置 --> <!-- <context-param> --> <!-- <param-name>log4jConfigLocation</param-name> --> <!-- <param-value>classpath:config/log4j.properties</param-value> --> <!-- </context-param> --> <!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 --> <!-- <context-param> --> <!-- <param-name>log4jRefreshInterval</param-name> --> <!-- <param-value>100000</param-value> --> <!-- </context-param> --> <!-- 加载其他配置文件至Spring应用上下文中 --> <!-- Spring 配置文件路径,此处可将Spring MVC的相关配置内容配置到Spring的配置文件applicationContext.xml中,共享同一个配置文件即可 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/applicationContext.xml</param-value> </context-param> <!-- Spring 容器监听器 配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- <listener> --> <!-- <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> --> <!-- </listener> --> <!-- <listener> --> <!-- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> --> <!-- </listener> --> <!-- <listener> --> <!-- <listener-class>org.springframework.web.util.WebAppRootListener</listener-class> --> <!-- </listener> --> <!-- <listener> --> <!-- <listener-class>com.test.service.cache.CacheListener</listener-class> --> <!-- </listener> --> <!-- 字符集 过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- tomcat关闭前先关闭quartz --> <!-- <listener> --> <!-- <listener-class>com.test.web.listener.ShutdownQuartzListener</listener-class> --> <!-- </listener> --> <!-- Spring view分发器 --> <!-- Spring mvc 配置,配置文件名称默认为{servlet-name}-servlet.xml,路径默认在/WEB-INF/下 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- <servlet-mapping> --> <!-- <servlet-name>dispatcher</servlet-name> --> <!-- <url-pattern>*.xls</url-pattern> --> <!-- </servlet-mapping> --> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> <welcome-file-list> <welcome-file>index</welcome-file> </welcome-file-list> <error-page> <error-code>400</error-code> <location>/error/400.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/error/403.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>405</error-code> <location>/error/405.jsp</location> </error-page> <error-page> <error-code>406</error-code> <location>/error/406.jsp</location> </error-page> <error-page> <error-code>412</error-code> <location>/error/412.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page> <error-page> <error-code>501</error-code> <location>/error/501.jsp</location> </error-page> <error-page> <error-code>502</error-code> <location>/error/502.jsp</location> </error-page> <error-page> <error-code>503</error-code> <location>/error/503.jsp</location> </error-page> </web-app>
3./src/main/resources/config/applicationContext.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:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd"> <description>Spring-web MVC配置</description> <context:component-scan base-package="com.test.service" /> <context:annotation-config /> <!-- 用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring bean对象 --> <!-- <bean class="com.xxl.app.base.SpringContextHolder" lazy-init="false" /> --> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:config/jdbc.properties</value> <!-- <value>classpath*:config/redis.properties</value> --> <value>classpath*:config/quartz.properties</value> <value>classpath*:config/log4j.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <!-- <bean class="com.test.util.WebAppContextUtil" /> --> <!-- <import resource="classpath*:config/spring-applicationContext-quartz.xml" /> --> <!-- redis --> <!-- <import resource="classpath*:config/spring-redis.xml" /> --> <!--创建tomcat jdbc pool数据源 --> <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <property name="validationQuery" value="select 1" /> <property name="validationInterval" value="30000" /> <property name="defaultAutoCommit" value="true" /> <property name="testWhileIdle" value="true" /> <property name="timeBetweenEvictionRunsMillis" value="1200000" /> <property name="minEvictableIdleTimeMillis" value="1800000" /> <property name="numTestsPerEvictionRun" value="5" /> </bean> <!-- 创建SqlSessionFactory,并指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 自动扫描mapping.xml文件,不需要mybatis的配置映射文件,扫描所有mapper文件,configLocation为mybatis属性,mapperLocations为所有mapper --> <property name="mapperLocations"> <list> <!-- 表示在包或以下所有目录中,以-mapper.xml结尾所有文件 --> <value>classpath:com/test/mappers/*-mapper.xml</value> </list> </property> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.test.model" /> </bean> <!-- Mapper文件扫描配置工具,Spring会自动扫描basePackage下所有dao接口,创建的代理类实现了IUserDAO接口,并且注入到应用程序中,这样不用写实现类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 自动扫描 mybatis的接口 --> <property name="basePackage" value="com.test.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 --> <tx:annotation-driven transaction-manager="txManager" /> </beans>
4./src/main/resources/config/springmvc-servlet.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> JSON转换器 </list> </property> </bean> --> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射,请求映射 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> --> <!-- 对所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.test.action" /> <!-- 启动基于Spring MVC的注解功能,激活@Controller,将控制器与方法映射加入到容器中 --> <mvc:annotation-driven /> <!-- 如果是根目录,重定向到WEB-INF/views/index --> <mvc:view-controller path="/" view-name="forward:/index" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <!-- <bean id="mappingJacksonHttpMessageConverter" --> <!-- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> --> <!-- <property name="supportedMediaTypes"> --> <!-- <list> --> <!-- <value>text/html;charset=UTF-8</value> --> <!-- </list> --> <!-- </property> --> <!-- </bean> --> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <!-- HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> --> <!-- <bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />处理.. <bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter" />处理.. --> <!--<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 只会拦截@RequestMapping的URL <property name="interceptors"> <list> <bean class="com.mvc.MyInteceptor"></bean> </list> </property> </bean> --> <!-- HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> --> <!--<bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > <property name="messageConverters"> <list> <ref bean="byteArray_hmc" /> <ref bean="string_hmc" /> </list> </property> </bean>--> <!-- 配置试图解析器 --> <!-- <bean id="viewResolver" --> <!-- class="org.springframework.web.servlet.view.InternalResourceViewResolver"> --> <!-- <property name="prefix" value="/WEB-INF/views/" /> --> <!-- <property name="suffix" value=".jsp" /> --> <!-- </bean> --> <!-- <bean id="viewResolverExcel" --> <!-- class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> --> <!-- <property name="order" value="1" /> --> <!-- <property name="basename" value="views" /> --> <!-- </bean> --> <!-- ViewResolver For FreeMarker --> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <!-- 模板后缀,指定html页面为模板 --> <property name="prefix" value="" /> <property name="suffix" value=".ftl" /> <property name="order" value="0" /> <property name="cache" value="true" /> <!-- 使用这个模板类来解析视图 --> <!-- <property name="viewClass" value="com.pingan.haofang.util.CommonFreeMarkerView" /> --> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" /> <property name="exposeSpringMacroHelpers" value="true" /> <!-- 允许访问请求属性,默认为false --> <property name="exposeRequestAttributes" value="true" /> <!-- 允许访问会话属性,默认为false --> <property name="exposeSessionAttributes" value="true" /> <!-- 页面上下文,类似于request.contextPath --> <property name="requestContextAttribute" value="rc" /> <!-- 模板输出内容编码,此处应与defaultEncoding保持一致 --> <property name="contentType" value="text/html;charset=UTF-8"></property> </bean> <!-- freemarker的配置 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <!-- 模板文件所在目录 --> <property name="templateLoaderPath" value="/WEB-INF/views/" /> <!-- FreeMarker环境属性配置 --> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">20</prop><!--刷新模板的周期,单位为秒,每隔20秒检查模板是否更新,单位为秒如果不经常更新模板可将更新的延迟时间设定长一点 --> <prop key="default_encoding">UTF-8</prop><!--指定FreeMarker模板文件的编码格式 --> <prop key="output_encoding">UTF-8</prop> <prop key="locale">zh-CN</prop><!-- 本地化设置,指定地区语言环境,我们的语言是中文 --> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="date_format">yyyy-MM-dd</prop> <prop key="time_format">HH:mm:ss</prop> <prop key="number_format">#.##########</prop> <prop key="boolean_format">true,false</prop> <prop key="whitespace_stripping">true</prop> <prop key="tag_syntax">auto_detect</prop> <prop key="url_escaping_charset">UTF-8</prop> <prop key="classic_compatible">true</prop> <prop key="template_exception_handler">ignore</prop> </props> </property> </bean> <!-- 对某些静态资源,如css,js,图片等进行过滤 ,有引用 "/res/**" 的路径引用转到工程的/res/目录取资源,cache-period启用浏览器缓存,上传的图片缓存1个月,其他js,css,img资源缓存一年 --> <mvc:resources mapping="/res/**" location="/WEB-INF/res/,/META-INF/res/" cache-period="31536000" /> <!-- <mvc:interceptors> --> <!-- <mvc:mapping path="/**" /> --> <!-- <mvc:exclude-mapping path="/user/*" /> --> <!-- <bean class="com.test.web.interceptor.PermissionInterceptor" /> --> <!-- </mvc:interceptor> --> <!-- </mvc:interceptors> --> <!-- 文件上传解析器 id 必须为multipartResolver,SpringMVC在超出上传文件限制时, 会抛出org.springframework.web.multipart.MaxUploadSizeExceededException, 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中, 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/messages" /> --> <!-- HttpMessageConverter用于将对象输出到客户端 --> <!-- <bean id="jsonmessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> --> <!-- </bean> --> <!-- 全局异常处理器 --> <!-- <bean id="handlerExceptionResolver" --> <!-- class="com.pingan.haofang.process.exception.ExceptionResolverCustom"> --> <!-- <property name="jsonmessageConverter" ref="jsonmessageConverter" /> --> <!-- </bean> --> <!--定义异常处理页面 --> <!-- <bean id="exceptionResolver" --> <!-- class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> --> <!-- <property name="exceptionMappings"> --> <!-- <props> --> <!-- <prop key="java.sql.SQLException">exception</prop> --> <!-- <prop key="java.io.IOException">exception</prop> --> <!-- <prop key="java.lang.IOException">exception</prop> --> <!-- <prop key="java.lang.NullPointerException">exception</prop> --> <!-- </props> --> <!-- </property> --> <!-- </bean> --> </beans>
5./src/main/resources/config/jdbc.properties文件内容:
jdbc.driver=com.mysql.jdbc.Driver #jdbc.driver=org.sqlite.JDBC jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #jdbc.url=jdbc:sqlite:D:/test.db jdbc.username=root jdbc.password=123456 #\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570 jdbc.initialSize=10 #\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570 jdbc.maxActive=20 #\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2 jdbc.maxIdle=20 #\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2 jdbc.minIdle=3 #\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4 jdbc.maxWait=60000 #\u81EA\u52A8\u6E05\u9664\u65E0\u7528\u8FDE\u63A5 jdbc.removeAbandoned=true #\u6E05\u9664\u65E0\u7528\u8FDE\u63A5\u7684\u7B49\u5F85\u65F6\u95F4 jdbc.removeAbandonedTimeout=180 #\u8FDE\u63A5\u5C5E\u6027 jdbc.connectionProperties="clientEncoding\=utf-8"
6./src/main/resources/config/log4j.properties文件内容:
#root directory for log files dir=..//Logs #log file for online file00=error.log #log file for batch file01=debug.log #log file size fileSize=10000KB #back up numbers for log file backup=10 ###########################default log level and log appender########################### log4j.rootLogger=console #log4j.logger.platform_debug=DEBUG,DEBUGFILE #log4j.logger.platform_error=ERROR,ERRORFILE #log4j.logger.platform_info=INFO,INFOFILE ######################################################################################## log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Target=System.out log4j.appender.console.ImmediateFlush=true log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%-5p][%t] method\:%l%n %m%n ######################################################################################## #log4j.appender.DEBUGFILE=org.apache.log4j.DailyRollingFileAppender #log4j.appender.DEBUGFILE.file=\\temp_space\\logs\\platform-debug.log #log4j.appender.DEBUGFILE.file=${dir}/debug.log #log4j.appender.DEBUGFILE.DatePattern='_'yyyy-MM-dd'.log' #log4j.appender.DEBUGFILE.layout=org.apache.log4j.PatternLayout #log4j.appender.DEBUGFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%-5p][%t] method\:%l%n %m%n ######################################################################################## log4j.appender.ERRORFILE=org.apache.log4j.DailyRollingFileAppender #log4j.appender.ERRORFILE.file=\\temp_space\\logs\\platform-error.log log4j.appender.ERRORFILE.file=/data/logs/platform-error.log log4j.appender.ERRORFILE.DatePattern='_'yyyy-MM-dd'.log' log4j.appender.ERRORFILE.layout=org.apache.log4j.PatternLayout log4j.appender.ERRORFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%-5p][%t] method\:%l%n %m%n ######################################################################################## #log4j.appender.SYSFILE=org.apache.log4j.DailyRollingFileAppender #log4j.appender.SYSFILE.file=\\temp_space\\logs\\platform-sys.log #log4j.appender.SYSFILE.file=/data/logs/platform-sys.log #log4j.appender.SYSFILE.DatePattern='_'yyyy-MM-dd'.log' #log4j.appender.SYSFILE.layout=org.apache.log4j.PatternLayout #log4j.appender.SYSFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%-5p][%t] method\:%l%n %m%n ######################################################################################## #log4j.appender.INFOFILE=org.apache.log4j.DailyRollingFileAppender #log4j.appender.INFOFILE.file=\\temp_space\\logs\\platform-info.log #log4j.appender.INFOFILE.file=/data/logs/platform-info.log #log4j.appender.INFOFILE.DatePattern='_'yyyy-MM-dd'.log' #log4j.appender.INFOFILE.layout=org.apache.log4j.PatternLayout #log4j.appender.INFOFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%-5p][%t] method\:%l%n %m%n ########################################################################################
7./src/main/resources/config/quartz.properties文件内容:
# Default Properties file for use by StdSchedulerFactory # to create a Quartz Scheduler Instance, if a different # properties file is not explicitly specified. # org.quartz.scheduler.instanceName: DefaultQuartzScheduler org.quartz.scheduler.rmi.export: false org.quartz.scheduler.rmi.proxy: false org.quartz.scheduler.wrapJobExecutionInUserTransaction: false org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount: 10 org.quartz.threadPool.threadPriority: 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true org.quartz.jobStore.misfireThreshold: 60000 org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
8./src/main/resources/config/redis.properties文件内容:
# Redis settings # server IP redis.host=127.0.0.1 # server port redis.port=6379 # server password redis.password=myredis # use dbIndex redis.pool.database=0 # \u63A7\u5236\u4E00\u4E2Apool\u6700\u591A\u6709\u591A\u5C11\u4E2A\u72B6\u6001\u4E3Aidle(\u7A7A\u95F2\u7684)\u7684jedis\u5B9E\u4F8B redis.pool.maxIdle=300 # \u8868\u793A\u5F53borrow(\u5F15\u5165)\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u6700\u5927\u7684\u7B49\u5F85\u65F6\u95F4\uFF0C\u5982\u679C\u8D85\u8FC7\u7B49\u5F85\u65F6\u95F4(\u6BEB\u79D2)\uFF0C\u5219\u76F4\u63A5\u629B\u51FAJedisConnectionException\uFF1B redis.pool.maxWait=3000 redis.pool.maxTotal=600 # \u5728borrow\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u662F\u5426\u63D0\u524D\u8FDB\u884Cvalidate\u64CD\u4F5C\uFF1B\u5982\u679C\u4E3Atrue\uFF0C\u5219\u5F97\u5230\u7684jedis\u5B9E\u4F8B\u5747\u662F\u53EF\u7528\u7684 redis.pool.testOnBorrow=true #\u6700\u5927\u5206\u914d\u7684\u5bf9\u8c61\u6570 redis.pool.maxActive=1024 #\u5f53\u8c03\u7528return Object\u65b9\u6cd5\u65f6\uff0c\u662f\u5426\u8fdb\u884c\u6709\u6548\u6027\u68c0\u67e5 redis.pool.testOnReturn=true
9./src/main/resources/config/spring-redis.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" 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-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 引入配置文件 --> <context:property-placeholder location="classpath*:config/redis.properties" /> <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 --> <!-- <cache:annotation-driven cache-manager="cacheManager" /> --> <!-- spring自己的缓存管理器,这里定义了两个缓存位置名称 ,既注解中的value --> <!-- <bean id="redisManager" class="org.springframework.cache.support.SimpleCacheManager"> --> <!-- <property name="caches"> --> <!-- <set> --> <!-- <bean class="org.cpframework.cache.redis.RedisCache"> --> <!-- <property name="redisTemplate" ref="redisTemplate" /> --> <!-- <property name="name" value="default"/> --> <!-- </bean> --> <!-- <bean class="org.cpframework.cache.redis.RedisCache"> --> <!-- <property name="redisTemplate" ref="redisTemplate02" /> --> <!-- <property name="name" value="commonCache"/> --> <!-- </bean> --> <!-- </set> --> <!-- </property> --> <!-- </bean> --> <!-- <bean id="redisCacheManager" class="com.pingan.haofang.service.impl.RedisCacheManger"> --> <!-- <property name="pool" ref="shardedJedisPool" /> --> <!-- </bean> --> <!-- jedis 连接池配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- <property name="maxActive" value="${redis.pool.maxActive}" /> --> <!-- <property name="maxWait" value="${redis.pool.maxWait}" /> --> <property name="maxTotal" value="${redis.pool.maxTotal}" /> <property name="maxIdle" value="${redis.pool.maxIdle}" /> <property name="maxWaitMillis" value="${redis.pool.maxWait}" /> <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> </bean> <!-- jedis 多个服务器配置 --> <bean id="jedisShardInfo" class="redis.clients.jedis.JedisShardInfo"> <constructor-arg index="0" value="${redis.host}" /> <constructor-arg index="1" value="${redis.port}" type="int" /> </bean> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1"> <list> <ref bean="jedisShardInfo" /> </list> </constructor-arg> </bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}" /> <property name="port" value="${redis.port}" /> <property name="password" value="${redis.password}" /> <property name="poolConfig" ref="jedisPoolConfig" /> <property name="shardInfo" ref="shardedJedisPool"></property> </bean> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="connectionFactory" p:keySerializer-ref="redisTemplateKeySerializer" p:valueSerializer-ref="redisTemplateValueSerializer" p:hashKeySerializer-ref="redisTemplateHashKeySerializer" p:hashValueSerializer-ref="redisTemplateHashValueSerializer"/> <bean id="redisTemplateKeySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> <bean id="redisTemplateValueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> <bean id="redisTemplateHashKeySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> <bean id="redisTemplateHashValueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </beans>10./src/main/java/com/test/model/User.java文件内容:
package com.test.model; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = 585953615014678681L; private int id; private String account; private String passwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } }
11./src/main/java/com/test/dao/IUserDao.java文件内容:
/src/main/java/com/test/service/IUserService.java文件内容:
package com.test.dao; import java.util.List; import java.util.HashMap; import org.apache.ibatis.annotations.Param; import com.test.model.User; public interface IUserDao { public boolean add(User user); public boolean adds(@Param("users")List<User> users); public boolean update(User user); public boolean delete(int id); public boolean deletes(@Param("users")List<Integer> users); public User findById(int id); public User login(HashMap<String, String> map); public List<User> findAllUser(); }
package com.test.service; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Param; import com.test.model.User; public interface IUserService { public boolean add(User user); public boolean adds(@Param("users")List<User> users); public boolean update(User user); public boolean delete(int id); public boolean deletes(@Param("users")List<Integer> users); public User findById(int id); public User login(HashMap<String, String> map); public List<User> findAllUser(); }
12./src/main/java/com/test/mappers/User-mapper.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.dao.IUserDao"> <resultMap type="User" id="UserResults"> <result property="id" column="uid" jdbcType="INTEGER" /> <result property="account" column="uname" jdbcType="VARCHAR" /> <result property="passwd" column="upasswd" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> uid, uname, upasswd </sql> <select id="findAllUser" resultMap="UserResults"> select <include refid="Base_Column_List" /> from users </select> <select id="findById" resultMap="UserResults" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from users where uid = #{id,jdbcType=INTEGER} </select> <select id="login" resultMap="UserResults" parameterType="User"> select <include refid="Base_Column_List" /> from users where uname = #{account,jdbcType=VARCHAR} and upasswd = #{passwd,jdbcType=VARCHAR} </select> <insert id="add" parameterType="User"> insert into users(uname, upasswd) values(#{account,jdbcType=VARCHAR},#{passwd,jdbcType=VARCHAR}) </insert> <insert id="adds" parameterType="java.util.List"> insert into users(uname, upasswd) values <foreach collection="users" item="user" index="index" separator=","> (#{user.account,jdbcType=VARCHAR},#{user.passwd,jdbcType=VARCHAR}) </foreach> </insert> <update id="update" parameterType="User"> update users <set> <!-- 这里要注意后面的 逗号“,” 因为有多个参数需要用逗号隔开 否则会报错 --> <if test="account != null"> uname = #{account,jdbcType=VARCHAR},</if> <if test="passwd != null"> upasswd = #{passwd,jdbcType=VARCHAR}</if> </set> where uid = #{id,jdbcType=INTEGER} </update> <delete id="delete" parameterType="java.lang.Integer"> delete from users where uid = #{id,jdbcType=INTEGER} </delete> <delete id="deletes" parameterType="java.util.List"> delete from users where uid in <foreach collection="users" item="id" index="index" open="(" separator="," close=")"> #{id,jdbcType=INTEGER} </foreach> </delete> </mapper>
13./src/main/java/com/test/action/HomeController.java文件内容:
package com.test.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/") public class HomeController { @RequestMapping(value = "/index", method = RequestMethod.GET) public ModelAndView getFirstPage(HttpServletRequest request) { // index就是视图的名称(index.ftl) ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); mv.setViewName("index"); session.setAttribute("title", "This is a freemaker test!"); return mv; } }
14./src/main/java/com/test/service/impl/UserServiceImpl.java文件内容:
package com.test.service.impl; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.dao.IUserDao; import com.test.service.IUserService; import com.test.model.User; @Service("userService") public class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; @Override public List<User> findAllUser() { return userDao.findAllUser(); } @Override public boolean add(User user) { return userDao.add(user); } @Override public boolean update(User user) { return userDao.update(user); } @Override public boolean delete(int id) { return userDao.delete(id); } @Override public User findById(int id) { return userDao.findById(id); } @Override public User login(HashMap<String, String> map) { return userDao.login(map); } @Override public boolean adds(@Param("users") List<User> users) { return userDao.adds(users); } @Override public boolean deletes(@Param("users") List<Integer> users) { return userDao.deletes(users); } }
15./src/main/java/com/test/action/UserController.java文件内容:
package com.test.action; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.test.model.User; import com.test.service.IUserService; @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private IUserService userService; // 用户登录 @RequestMapping(value = "/login", method = RequestMethod.POST) public String login( HttpServletRequest request, @RequestParam(value = "account", required = true, defaultValue = "test") String uname, @RequestParam(value = "passwd", required = true, defaultValue = "test") String upasswd) { HashMap<String, String> map = new HashMap<String, String>(); map.put("account", uname); map.put("passwd", upasswd); HttpSession session = request.getSession(); User user = userService.login(map); if (user != null) { session.setAttribute("loginStatus","OK"); return "redirect:/user/userList"; } else { session.setAttribute("loginStatus", "用户名或密码错误"); return "/index"; } } // 用户列表 @RequestMapping(value = "/userList") public ModelAndView listAll() { ModelAndView MV = new ModelAndView("user/user_list"); List<User> userList = userService.findAllUser(); MV.addObject("users", userList); return MV; } // 新增用户 @RequestMapping(value = "/insertuser", method = RequestMethod.POST) public String insert(HttpServletRequest request, User user) { HttpSession session = request.getSession(); session.removeAttribute("loginError"); session.removeAttribute("delStatus"); session.removeAttribute("updateStatus"); if (user != null && user.getAccount().trim().length() > 0 && user.getPasswd().trim().length() > 0) { boolean result = userService.add(user); if (result) { session.setAttribute("insertStatus", "添加成功!"); } else { session.setAttribute("insertStatus", "添加失败!"); } } else { session.setAttribute("insertStatus", "添加失败,用户名或密码为空!"); } return "redirect:/user/userList"; } // 查找用户 @RequestMapping(value = "/findUser") public ModelAndView find(@RequestParam(value = "id") int id) { ModelAndView mv = new ModelAndView("user/update"); User user = userService.findById(id); mv.addObject("user", user); return mv; } // 更新用户信息 @RequestMapping(value = "/updateUser", method = RequestMethod.POST) public String updateUser(HttpServletRequest request, User userInfo) { boolean result = userService.update(userInfo); HttpSession session = request.getSession(); if (result) { session.removeAttribute("insertStatus"); session.removeAttribute("delStatus"); session.setAttribute("updateStatus", "修改成功!"); } return "redirect:/user/userList"; } // 删除用户 @RequestMapping(value = "/deleteUser") public String deleteuser(HttpServletRequest request, @RequestParam(value = "id") int id) { boolean result = userService.delete(id); HttpSession session = request.getSession(); if (result) { session.removeAttribute("insertStatus"); session.removeAttribute("updateStatus"); session.setAttribute("delStatus", "删除成功!"); } return "redirect:/user/userList"; } // 注销 @RequestMapping(value = "/clear") public String clear(HttpServletRequest request) { HttpSession session = request.getSession(); session.invalidate(); return "redirect:/"; } }
16.Junit测试文件内容:
package RedisTest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import com.test.model.User; import com.test.service.IUserService; @ContextConfiguration(locations={"classpath:config/applicationContext.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @Transactional //如果是true不会改变数据库数据,如果是false会改变数据 @TransactionConfiguration(transactionManager="txManager",defaultRollback=false) public class MyBatisTest { @Autowired private IUserService userService; /** * 登录 */ @Test public void login() { HashMap<String, String> map=new HashMap<String, String>(); map.put("account", "root"); map.put("passwd", "root"); User user = userService.login(map); System.out.println("用户名:"+user.getAccount()+"\n密码:"+user.getPasswd()); } /** * 新增 * 运行时间0.542秒 */ @Test public void testAddUser() { User user = new User(); user.setAccount("user1"); user.setPasswd("test1"); boolean result = userService.add(user); Assert.assertTrue(result); } /** * 批量新增 普通方式 * 开始时间:1459563108708 结束时间:1459563117616 时间差:8908毫秒 * 运行时间10.010秒 */ @Test public void testAddUsers1() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 50010; i++) { User user = new User(); user.setAccount("user"+ i); user.setPasswd("test"+ i); list.add(user); } long begin = System.currentTimeMillis(); for (User user : list) { userService.add(user); } long end = System.currentTimeMillis(); System.out.println("开始时间:"+begin+" 结束时间:"+end +" 时间差:" +(end - begin)); } /** * 批量新增 数据库批量方式 * 开始时间:1459563210579 结束时间:1459563213050 时间差:2471毫秒 * 运行时间3.265秒 */ @Test public void testAddUsers2() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 50010; i++) { User user = new User(); user.setAccount("user"+ i); user.setPasswd("test"+ i); list.add(user); } long begin = System.currentTimeMillis(); boolean result = userService.adds(list); long end = System.currentTimeMillis(); System.out.println("开始时间:"+begin+" 结束时间:"+end +" 时间差:" +(end - begin)); Assert.assertTrue(result); } /** * 修改 * 运行时间0.645秒 */ @Test public void testUpdate() { User user = userService.findById(4); user.setPasswd("new_password"); boolean result = userService.update(user); Assert.assertTrue(result); } /** * 根据id查找 * 运行时间0.361秒 */ @Test public void testGetUserById() { int id = 4; User user = userService.findById(id); Assert.assertNotNull(user); Assert.assertEquals(user.getPasswd(), "new_password"); } /** * 通过id删除单个 * 运行时间0.633秒 */ @Test public void testDelete() { int id = 981; boolean result = userService.delete(id); Assert.assertTrue(result); } /** * 批量删除 普通方式 * 开始时间:1459563760155 结束时间:1459563768336 时间差:8181毫秒 * 运行时间8.958秒 */ @Test public void testDeletes1() { List<Integer> list = new ArrayList<Integer>(); for (int i = 10; i < 50010; i++) { list.add(i); } long begin = System.currentTimeMillis(); for (Integer id : list) { userService.delete(id); } long end = System.currentTimeMillis(); System.out.println("开始时间:"+begin+" 结束时间:"+end +" 时间差:" +(end - begin)); } /** * 批量删除 数据库批量方式 * 开始时间:1459563867103 结束时间:1459563868846 时间差:1743毫秒 * 运行时间2.404秒 */ @Test public void testDeletes2() { List<Integer> list = new ArrayList<Integer>(); for (int i = 10; i < 50010; i++) { list.add(i); } long begin = System.currentTimeMillis(); boolean result = userService.deletes(list); long end = System.currentTimeMillis(); System.out.println("开始时间:"+begin+" 结束时间:"+end +" 时间差:" +(end - begin)); Assert.assertTrue(result); } }
17./src/main/webapp/WEB-INF/views/index.ftl文件内容:
<!DOCTYPE html> <#import "spring.ftl" as s /> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>首页</title> <script type="text/javascript" src="<@s.url '/res/jquery-1.11.3.js'/>"></script> <script type="text/javascript"> $(function() { $("#btn").on("click",function() { htmlobj = $.ajax({url : "<@s.url '/res/demo_test.txt'/>",async : false}); $("#results").append(htmlobj.responseText + "<br />"); params = $("#loginForm").serializeArray(); //var stack =JSON.stringify(params); $.each(params, function(i, field) { $("#results").append(field.name + ":" + field.value + "<br />"); if (isEmpty(field.value)) { return;//验证是否为空 } }); //$.ajax({type: "POST",url:"user/login",async:false,data: params}); /* $.post("user/login", params,function(data,status){ var loginStatus=""; <#if loginStatus??> loginStatus+='${loginStatus}'; </#if> if(status == "success" && !isEmpty(loginStatus) && loginStatus !="用户名或密码错误"){ document.write(data); window.location.href="user/userList"; } },"text"); */ $("#loginForm").attr("action", "user/login"); $("#loginForm").submit(); }); }) //非空判断 function isEmpty(strIn) { if (strIn === undefined) { return true; } else if (strIn == null) { return true; } else if (strIn == "") { return true; } else { return false; } } function check(obj) { var content = obj.val(); var attribute = obj.attr("name"); if (attribute == "account" && !content) {//验证用户名是否为空 $("#msg1").val("用户名不能为空!"); $("#account").focus(); } else { $("#msg1").val(""); } if (attribute == "passwd" && !content) {//验证密码是否为空 $("#msg2").val("密码不能为空!"); $("#passwd").focus(); } else { $("#msg2").val(""); } } </script> <style type="text/css"> .textStyle{font-size: 20px;color: red;} </style> </head> <body> <p class="textStyle">Hello!${title}</p> <div align="center"><img src = "<@s.url '/res/images/img1.jpg'/>" height="200px" width="400px"/></div> <!-- action="user/login" --> <form method="post" id="loginForm" action=""> <br>用户名: <input type="text" id="account" maxlength="16" name="account" value="" onblur="check($(this))" /> <span id="msg1" class="textStyle"></span> <br>密码: <input type="password" id="passwd" maxlength="16" name="passwd" value="" onblur="check($(this))"/> <span id="msg2" class="textStyle"></span> <br><input type="reset" value="重置" /> <input id="btn" type="button" value="登录" /> </form> <br /> <div class="textStyle"> <p id="results" ></p><br /> <#if loginStatus??> ${loginStatus} </#if> </div> </body> </html>18./src/main/webapp/WEB-INF/views/user/user_list.ftl文件内容;
<#setting classic_compatible=true> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>用户列表</title> <style type="text/css"> <!-- .STYLE1 { font-family: Arial, Helvetica, sans-serif,新宋体; font-weight: bold; font-size: 26px; color: #FF0000; } .STYLE13 { font-size: 22 } .STYLE15 { font-family: Arial, Helvetica, sans-serif; font-size: 20px; } --> </style> </head> <body> <form action="insertuser" method="post"> <table> <tr> <th>账号</th> <td><input type="text" name="account" /></td> </tr> <tr> <th>密码</th> <td><input type="text" name="passwd" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="添加"></td> </tr> </table> </form> <table width="900" height="500" border="2" cellpadding="0" cellspacing="1" align="center"> <tr> <td colspan="4" height="40" align="center" valign="middle"><span class="STYLE1">用户列表</span></td> </tr> <tr> <td width="150" height="30" align="center" valign="middle"><span class="STYLE15">账号</span></td> <td width="150" height="30" align="center" valign="middle"><span class="STYLE15">密码</span></td> <td colspan="2" width="120" height="30" align="center" valign="middle"><span class="STYLE15">功能</span></td> </tr> <#list users as user> <tr> <td width="150" height="30" align="center" valign="middle"><span class="STYLE15">${user.account}</span></td> <td width="150" height="30" align="center" valign="middle"><span class="STYLE15">${user.passwd}</span></td> <td width="60" height="30" align="center" valign="middle"><a href="findUser?id=${user.id}">修改</a></td> <td width="60" height="30" align="center" valign="middle"><a href="deleteUser?id=${user.id}">删除</a></td> </tr> </#list> </table> <br /> <div align="center"> <a href="clear">注销</a> </div> <br /> <#if updateStatus??> <div align="center"> <font color="red">${updateStatus}</font> </div> </#if> <#if insertStatus??> <div align="center"> <font color="red">${insertStatus}</font> </div> </#if> <#if delStatus??> <div align="center"> <font color="red">${delStatus}</font> </div> </#if> </body> </html>
19./src/main/webapp/WEB-INF/views/user/update.ftl文件内容:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>更新用户信息</title> </head> <body> <form action="updateUser" method="post"> <input type="hidden" name="id" value="${user.id}" /> <table> <tr> <th>账号</th> <td><input type="text" name="account" value="${user.account}" /></td> </tr> <tr> <th>密码</th> <td><input type="text" name="passwd" value="${user.passwd}" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="修改"></td> </tr> </table> </form> </body> </html>20./src/main/webapp/WEB-INF/res/jquery-1.11.3.js