1.添加依赖
<?xml version="1.0" encoding="UTF-8"?> <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>com.star</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <!--spring--> <spring.version>5.0.2.RELEASE</spring.version> <!--mybatis--> <mybatis.version>3.4.5</mybatis.version> <!--mysql--> <mysql.version>5.1.44</mysql.version> <!--pageHelper--> <pagehelper.version>5.1.2</pagehelper.version> <!--mybatis-spring--> <mybatis.spring.version>1.3.1</mybatis.spring.version> <!--dbcp2(数据库连接池)--> <commons.dbcp2.version>2.1.1</commons.dbcp2.version> <commons.pool2.version>2.4.3</commons.pool2.version> <!--log4j2--> <log4j2.version>2.9.1</log4j2.version> <!--junit+servlet--> <junit.version>4.13</junit.version> <servlet.version>4.0.1</servlet.version> <!--lombok--> <lombok.version>1.18.10</lombok.version> <!--redis--> <jedis.version>2.9.0</jedis.version> <!--spring-data-redis--> <spring-data-redis.version>1.7.1.RELEASE</spring-data-redis.version> <mybatis-redis.version>1.0.0-beta2</mybatis-redis.version> <!--slf4j--> <slf4j.version>1.7.7</slf4j.version> <log4j2.version>2.9.1</log4j2.version> <disruptor.version>3.2.0</disruptor.version> <!--jackson--> <jackson.version>2.9.3</jackson.version> <!--shiro--> <shiro.version>1.2.5</shiro.version> </properties> <dependencies> <!--spring--> <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-orm</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-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--springMVC--> <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> </dependency> <!-- shiro核心包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!-- 添加shiro web支持 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <!--添加shiro的spring支持--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!--dbcp2--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons.dbcp2.version}</version> <exclusions> <exclusion> <artifactId>commons-pool2</artifactId> <groupId>org.apache.commons</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons.pool2.version}</version> </dependency> <!-- ********************** 日志配置 ********************** --> <!--记得修改mybatis.cfg.xml添加如下内容--> <!--<setting name="logImpl" value="SLF4J"/>--> <!-- log配置:Slf4j+Log4j2 --> <!--1) slf4j核心包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!--2) 用于与slf4j保持桥接--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!--3) 核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <!--4) web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> <scope>runtime</scope> </dependency> <!--5) 需要使用log4j2的AsyncLogger需要包含disruptor--> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>${disruptor.version}</version> </dependency> <!--junit+servlet--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <!-- spring-test的结合 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> <exclusions> <exclusion> <artifactId>commons-pool2</artifactId> <groupId>org.apache.commons</groupId> </exclusion> </exclusions> </dependency> <!-- spring-data-redis 依赖--> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-redis</artifactId> <version>${mybatis-redis.version}</version> <exclusions> <exclusion> <artifactId>jedis</artifactId> <groupId>redis.clients</groupId> </exclusion> </exclusions> </dependency> <!-- spring-data-redis 依赖--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <!--<version>1.7.1.RELEASE</version>--> <version>${spring-data-redis.version}</version> <exclusions> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-aop</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-tx</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>jcl-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!--jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> <exclusions> <exclusion> <artifactId>jackson-annotations</artifactId> <groupId>com.fasterxml.jackson.core</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!--********************文件上传下载依赖************************--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!-- ********************** JSTL依赖 ********************** --> <!-- 缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config--> <!-- 原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!--********************hibernate-validator验证器************************--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version> </dependency> </dependencies> <build> <finalName>ssm</finalName> <plugins> <!--第一步就是配置maven-compiler-plugin插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.4.2</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> </plugins> </build> </project>
2.配置文件相关
1)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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--配置多properties文件方式--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:redis.properties</value> </list> </property> </bean> <import resource="spring/spring-mybatis.xml"/> <import resource="spring/spring-redis.xml"/> <import resource="spring/spring-shiro.xml"/> </beans>
2)日志log4j2.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. --> <Configuration status="WARN" monitorInterval="30"> <Properties> <!-- 配置日志文件输出目录 ${sys:user.home} --> <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property> <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property> <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property> <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property> </Properties> <Appenders> <!--这个输出控制台的配置 --> <Console name="Console" target="SYSTEM_OUT"> <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" /> <!-- 输出日志的格式 --> <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 --> <PatternLayout pattern="${PATTERN}" /> </Console> <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 --> <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true --> <File name="log" fileName="logs/test.log" append="false"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </File> <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 --> <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. --> <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 --> <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. --> <!-- <SizeBasedTriggeringPolicy size="2 kB" /> --> </Policies> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log" filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="2 kB" /> </Policies> <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 --> <DefaultRolloverStrategy max="20" /> </RollingFile> <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log" filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- <SizeBasedTriggeringPolicy size="10 MB" /> --> </Policies> </RollingFile> </Appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 --> <Loggers> <!--过滤掉spring和mybatis的一些无用的DEBUG信息 --> <logger name="org.springframework" level="INFO"></logger> <logger name="org.mybatis" level="INFO"></logger> <!-- 第三方日志系统 --> <logger name="org.springframework" level="ERROR" /> <logger name="org.hibernate" level="ERROR" /> <logger name="org.apache.struts2" level="ERROR" /> <logger name="com.opensymphony.xwork2" level="ERROR" /> <logger name="org.jboss" level="ERROR" /> <!-- 配置日志的根节点 --> <root level="all"> <appender-ref ref="Console" /> <appender-ref ref="RollingFileInfo" /> <appender-ref ref="RollingFileWarn" /> <appender-ref ref="RollingFileError" /> </root> </Loggers> </Configuration>
3)spring-mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--1. 注解式开发 --> <!-- 注解驱动开启 --> <context:annotation-config/> <!-- 用注解方式注入bean,并指定查找范围:com.zking.ssh2及子子孙孙包,使用默认扫描方式,但是跳过spring的controller注解--> <context:component-scan base-package="com.star" use-default-filters="true"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2.引入外部jdbc配置文件--> <!--<context:property-placeholder location="classpath:jdbc.properties"/>--> <!--3.配置dbcp2连接池数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" 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="initialSize" value="${jdbc.initialSize}"/> <!--最大活动连接数--> <property name="maxTotal" value="${jdbc.maxTotal}"/> <!--最大空闲连接数--> <property name="maxIdle" value="${jdbc.maxIdle}"/> <!--最小空闲连接数--> <property name="minIdle" value="${jdbc.minIdle}"/> <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。--> <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常--> <property name="maxWaitMillis" value="${jdbc.maxWaitMillis}"/> </bean> <!--4. spring和MyBatis整合 --> <!--1) 创建sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描XxxMapping.xml文件,**任意路径 --> <property name="mapperLocations" value="classpath:cn/star/mapper/*Mapper.xml"/>
<!-- 指定别名 --> <property name="typeAliasesPackage" value="com/star/**/model"/> <!--配置pagehelper插件--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql </value> </property> </bean> </array> </property> <!-- 添加mybatis的初始化相关配置 --> <property name="configuration"> <bean class="org.apache.ibatis.session.Configuration"> <!-- 开启驼峰命名法,默认是false --> <property name="mapUnderscoreToCamelCase" value="true"/> <!-- 查询时,关闭关联对象的及时加载以提高性能 --> <property name="lazyLoadingEnabled" value="false"/> <!-- 设置关联关系时的对象形态以提高性能,此处为按需加载字段(sql指定字段),不会加载关联表的关联字段 --> <property name="aggressiveLazyLoading" value="true"/> <!-- 全局映射器启用缓存,提高性能 --> <property name="cacheEnabled" value="true"/> </bean> </property> </bean> <!--2) 自动扫描com/zking/oa/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,--> <!-- 即可直接在程序中使用dao接口,不用再获取sqlsession对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--basePackage 属性是映射器接口文件的包路径。--> <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径--> <property name="basePackage" value="com/star/**/mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 5. 注解式事物配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启注解式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 6. 开启动态代理 --> <aop:aspectj-autoproxy/> </beans>
4)spring-redis.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:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- 导入redis依赖(jedis和spring-redis集成jar包) 1.导入数据库外部文件redis.properties 2.创建数据库连接池 3.创建Redis连接工厂 4.创建RedisTemplate模板 5.配置缓存管理器 --> <!-- redis的相关配置已经在applicationContext.xml导入了,因为spring只允许有一个context:property-placeholder --> <!-- 所以下面的配置会注释掉了 --> <!-- 1. 引入properties配置文件 --> <!--<context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties" />--> <!-- 2. redis连接池配置--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--最大空闲数--> <property name="maxIdle" value="${redis.maxIdle}"/> <!--连接池的最大数据库连接数 --> <property name="maxTotal" value="${redis.maxTotal}"/> <!--最大建立连接等待时间--> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/> <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)--> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/> <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3--> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/> <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1--> <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/> <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个--> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> <!--在空闲时检查有效性, 默认false --> <property name="testWhileIdle" value="${redis.testWhileIdle}"/> </bean> <!-- 3. redis连接工厂 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="poolConfig"/> <!--IP地址 --> <property name="hostName" value="${redis.hostName}"/> <!--端口号 --> <property name="port" value="${redis.port}"/> <!--如果Redis设置有密码 --> <property name="password" value="${redis.password}"/> <!--客户端超时时间单位是毫秒 --> <property name="timeout" value="${redis.timeout}"/> </bean> <!-- 4. redis操作模板,使用该对象可以操作redis --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! --> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> </property> <!--开启事务 --> <property name="enableTransactionSupport" value="false"/> </bean> <!--5.配置缓存管理器--> <!--CacheManager ->Cache ->Element--> <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg name="redisOperations" ref="redisTemplate" /> <!--redis缓存数据过期时间单位秒--> <property name="defaultExpiration" value="${redis.expiration}" /> <property name="usePrefix" value="true"/> <property name="cachePrefix"> <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix"> <constructor-arg index="0" value="-cache-"/> </bean> </property> </bean> <!--6.配置自定义key生成器CacheKeyGenerator--> <bean id="cacheKeyGenerator" class="com.star.util.CacheKeyGenerator"/> <!--7.启用缓存注解功能--> <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/> </beans>
5)spring-shiro.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--1) 配置自定义Realm--> <bean id="shiroRealm" class="com.star.shiro.ShiroRealm"> <!--注意:重要~~~~~此处加密方式要与用户注册时的算法一致 --> <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密--> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!--指定hash算法为MD5--> <property name="hashAlgorithmName" value="md5"/> <!--指定散列次数为1024次--> <property name="hashIterations" value="1024"/> <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储--> <property name="storedCredentialsHexEncoded" value="true"/> </bean> </property> </bean> <!--2) 注册安全管理器将自定义的Realm设置到Shiro的SecurityManager中,在Shiro授权和认证时使用自定义的Realm数据源进行校验--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroRealm" /> </bean> <!--3) 配置Shiro核心过滤器Shiro核心过滤器用于拦截请求,通过给定的授权认证机制对用户访问身份和权限进行认证识别--> <!--Shiro核心过滤器--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager" /> <!-- 身份验证失败,跳转到登录页面 --> <property name="loginUrl" value="/"/> <!-- 身份验证成功,跳转到指定页面 --> <property name="successUrl" value="/input/home"/> <!-- 权限验证失败,跳转到指定页面 --> <property name="unauthorizedUrl" value="/login.jsp"/> <!-- Shiro连接约束配置,即过滤链的定义 --> <property name="filterChainDefinitions"> <value> <!--anon 表示匿名访问,不需要认证以及授权--> <!--authc表示需要认证 没有进行身份认证是不能进行访问的--> /sysUser/userLogin=anon /book/**=authc <!-- /css/** = anon /images/** = anon /js/** = anon / = anon /user/logout = logout /user/** = anon /userInfo/** = authc /dict/** = authc /console/** = roles[admin] /** = anon--> </value> </property> </bean> <!-- 4) 配置Shiro生命周期--> <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>
6)mybatis代码生成配置generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置--> <classPathEntry location="D:/softWare/repository/mvn_repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar"/> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 01 指定javaBean生成的位置 --> <!-- targetPackage:指定生成的model生成所在的包名 --> <!-- targetProject:指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.star.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="true"/> <!-- 是否对model添加构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="false"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.star.mapper" targetProject="src/main/resources"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 03 生成XxxMapper接口 --> <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.star.mapper" targetProject="src/main/java" type="XMLMAPPER"> <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 --> <!-- tableName为对应的数据库表 --> <!-- domainObjectName是要生成的实体类 --> <!-- enable*ByExample是否生成 example类 --> <!--enableCountByExample="false" enableDeleteByExample="false"--> <!--enableSelectByExample="false" enableUpdateByExample="false">--> <!-- 需要几个表就添加几个 --> <table schema="" tableName="t_sys_user" domainObjectName="SysUser" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> <table schema="" tableName="t_sys_role" domainObjectName="SysRole" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> <table schema="" tableName="t_sys_permission" domainObjectName="SysPermission" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> <table schema="" tableName="t_sys_user_role" domainObjectName="SysUserRole" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> <table schema="" tableName="t_sys_role_permission" domainObjectName="SysUserRolePermission" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> <!--<table schema="" tableName="t_category" domainObjectName="Category" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!– 忽略列,不生成bean 字段 –> <!– <ignoreColumn column="FRED" /> –> <!– 指定列的java数据类型 –> <!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –> </table>--> </context> </generatorConfiguration>
7)数据库配置jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false jdbc.username=root jdbc.password=123456 jdbc.initialSize=10 jdbc.maxTotal=100 jdbc.maxIdle=50 jdbc.minIdle=10 jdbc.maxWaitMillis=-1
8)redis配置redis.properties:
#ip地址 redis.hostName=192.168.109.130 #端口号 redis.port=6379 #如果有密码 redis.password=123456 #客户端超时时间单位是毫秒 默认是2000 redis.timeout=10000 #redis缓存数据过期时间单位秒 redis.expiration=3600 ##################### redis连接池配置 ########################################### #最大空闲数 redis.maxIdle=300 #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal #redis.maxActive=600 #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性 redis.maxTotal=1000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 redis.maxWaitMillis=1000 #连接的最小空闲时间 默认1800000毫秒(30分钟) redis.minEvictableIdleTimeMillis=300000 #每次释放连接的最大数目,默认3 redis.numTestsPerEvictionRun=1024 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 redis.timeBetweenEvictionRunsMillis=30000 #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 redis.testOnBorrow=true #在空闲时检查有效性, 默认false redis.testWhileIdle=true #redis集群配置 #redis.sentinel.host1=172.20.1.230 #redis.sentinel.port1=26379 #redis.sentinel.host2=172.20.1.231 #redis.sentinel.port2=26379 #redis.sentinel.host3=172.20.1.232 #redis.sentinel.port3=26379
web相关配置
1)web.xml:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>home</welcome-file> </welcome-file-list> <!--禁止自动初始化log4j2 --> <context-param> <param-name>isLog4jAutoInitializationDisabled</param-name> <param-value>false</param-value> </context-param> <!-- Spring和web项目集成start --> <!-- spring上下文配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 读取Spring上下文的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring和web项目集成end --> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 中文乱码处理 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- shiro过滤器定义 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 --> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <!--web.xml 3.0的新特性,是否支持异步--> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2)spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--配置默认首页--> <!-- <mvc:view-controller path="/" view-name="home" />--> <!--1)防止重复扫描,只扫描包含controller的注解--> <context:component-scan base-package="com.star" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,--> <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)--> <mvc:annotation-driven/> <!--3) 视图解析器ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4) 单独处理图片、样式、js等资源 --> <!-- <mvc:resources location="/css/" mapping="/css/**"/>--> <!-- <mvc:resources location="/js/" mapping="/js/**"/>--> <mvc:resources location="WEB-INF/images/" mapping="/images/**"/> <!--5)配置国际化资源文件 ,必须叫messageSource--> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>i18n</value> </list> </property> </bean> <!--6) 指定语言区域解析器,由它来确定使用哪个语言 ,必须叫localeResolver--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/> <!--7) 配置国际化操作拦截器--> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> </mvc:interceptors> <!--8) 配置文件上传下载解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"/> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"/> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean> <!--9) 配置RequestMappingHandlerAdapter覆盖默认的适配器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter"/> </list> </property> </bean> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件--> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </beans>
集成完毕。
classpath:cn/sxt/mapper/*Mapper.xml