系统搭建的配置大同小异,本文在前人的基础上做了些许的改动,重写数据库,增加依据权限的动态菜单的实现,也增加了后台返回json格式数据的配置,详细参见完整源码。
主要的后端架构:Spring+SpringMVC+Mybatis+Shiro+Maven
IDE:IntelliJ IDEA 15.0.2
jdk:1.8.0_66
系统完整源码
https://github.com/Wellat/Factor
系统目录结构
跑起来效果
搭建步骤
1、用Idea创建maven项目
2、配置pom.xml文件,添加依赖
<?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.hemi</groupId>
<artifactId>factor</artifactId>
<version>1.0.0</version>
<packaging>war</packaging> <build>
<finalName>factor</finalName>
<plugins>
<!-- Mybatis generator代码生成插件 配置 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>${plugin.mybatis.generator}</version>
<configuration>
<configurationFile>${mybatis.generator.generatorConfig.xml}</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin> <!--Maven编译插件 配置-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${plugin.maven-compiler}</version>
<configuration>
<source>${project.build.jdk}</source>
<target>${project.build.jdk}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins> <!--配置Maven 对resource文件 过滤 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build> <properties>
<!-- base setting -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.locales>zh_CN</project.build.locales>
<project.build.jdk>1.8</project.build.jdk> <!-- plugin setting -->
<mybatis.generator.generatorConfig.xml>${basedir}/src/test/resources/generatorConfig.xml</mybatis.generator.generatorConfig.xml>
<mybatis.generator.generatorConfig.properties>file:///${basedir}/src/test/resources/generatorConfig.properties</mybatis.generator.generatorConfig.properties> <!-- plugin versions -->
<plugin.mybatis.generator>1.3.1</plugin.mybatis.generator>
<plugin.maven-compiler>3.1</plugin.maven-compiler> <!-- lib versions -->
<junit.version>4.11</junit.version>
<spring.version>4.1.6.RELEASE</spring.version>
<mybatis.version>3.2.2</mybatis.version>
<mybatis.spring.version>1.2.2</mybatis.spring.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
<postgresql.version>9.1-901.jdbc4</postgresql.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<httpclient.version>4.1.2</httpclient.version>
<jackson.version>1.9.13</jackson.version>
<c3p0.version>0.9.1.2</c3p0.version>
<druid.version>1.0.5</druid.version>
<tomcat.jdbc.version>7.0.53</tomcat.jdbc.version>
<jstl.version>1.2</jstl.version>
<google.collections.version>1.0</google.collections.version>
<cglib.version>3.1</cglib.version>
<shiro.version>1.2.3</shiro.version>
<commons.fileupload.version>1.3.1</commons.fileupload.version>
<commons.codec.version>1.9</commons.codec.version>
<commons.net.version>3.3</commons.net.version>
<aspectj.version>1.6.12</aspectj.version>
<netty.version>4.0.18.Final</netty.version>
<hibernate.validator.version>5.1.1.Final</hibernate.validator.version>
<redis.version>2.8.1</redis.version>
<fastjson.version>1.2.17</fastjson.version>
</properties> <dependencies> <!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency> <!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</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-context-support</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end --> <!-- mybatis start-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!--mybatis end--> <!-- mysql-connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency> <!-- DruidDataSource -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency> <!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</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 --> <!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency> <!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency> <!-- start apache -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version>
</dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency> <dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons.codec.version}</version>
</dependency> <dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons.net.version}</version>
</dependency> <dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency> <!-- end apache --> <!-- google -->
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>${google.collections.version}</version>
</dependency> <!-- cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency> <!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>${shiro.version}</version>
</dependency> <!-- aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency> <!-- hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency> <!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency> <dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
<type>jar</type>
<scope>test</scope>
</dependency> </dependencies> </project>
pom.xml
3、配置web.xml
在系统 src/main 下创建 webapp/WEB-INF 二级目录,在WEB-INF下创建web.xml文件
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Spring -->
<!-- 配置Spring配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:applicationContext.xml
classpath*:applicationContext-shiro.xml
</param-value>
</context-param>
<!-- 配置Spring上下文监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring --> <!-- 配置Spring字符编码过滤器 -->
<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> <!-- shiro 安全过滤器 -->
<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->
<!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->
<!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->
<!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!--<async-supported>true</async-supported>-->
<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> <!-- 配置log4j配置文件路径 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 60s 检测日志配置 文件变化 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param> <!-- 配置Log4j监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <!-- Spring MVC 核心控制器 DispatcherServlet 配置 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!-- 拦截所有/rest/* 的请求,交给DispatcherServlet处理,性能最好 -->
<url-pattern>/rest/*</url-pattern>
</servlet-mapping> <!-- 首页 -->
<welcome-file-list>
<welcome-file>rest/index</welcome-file>
</welcome-file-list> <!-- 错误页 -->
<error-page>
<error-code>404</error-code>
<location>/rest/page/401</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/rest/page/500</location>
</error-page>
<error-page>
<exception-type>org.apache.shiro.authz.AuthorizationException</exception-type>
<location>/rest/page/401</location>
</error-page> </web-app>
web.xml
4、配置Spring
①applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- 自动扫描quick4j包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="com.hemi.factor"></context:component-scan> <!-- 引入配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:application.properties</value>
</list>
</property>
</bean> <!-- dataSource 配置 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${ds.initialSize}"/>
<property name="minIdle" value="${ds.minIdle}"/>
<property name="maxActive" value="${ds.maxActive}"/> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${ds.maxWait}"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/> <property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
</bean> <!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"
p:configLocation="classpath:mybatis-config.xml"
p:mapperLocations="classpath:com/hemi/factor/web/dao/*.xml"/> <!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.hemi.factor.web.dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- 对dataSource 数据源进行事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/> <!-- 事务管理 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 -->
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<!-- select,count开头的方法,开启只读,提高数据库访问性能 -->
<tx:method name="select*" read-only="true"/>
<tx:method name="count*" read-only="true"/>
<!-- 对其他方法 使用默认的事务管理 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice> <!-- 事务 aop 配置 -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* com.hemi.factor.web.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config> <!-- 配置使Spring采用CGLIB代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 启用对事务注解的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- Cache配置 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehCacheManagerFactory"/>
</beans>
applicationContext.xml
②application.properties
含数据库连接设置
##JDBC Global Setting
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/factor?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=hemi ##DataSource Global Setting #配置初始化大小、最小、最大
ds.initialSize=1
ds.minIdle=1
ds.maxActive=20 #配置获取连接等待超时的时间
ds.maxWait=60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
ds.timeBetweenEvictionRunsMillis=60000 #配置一个连接在池中最小生存的时间,单位是毫秒
ds.minEvictableIdleTimeMillis=300000
application.properties
③ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="txswx-ehcache">
<diskStore path="java.io.tmpdir"/>
<!-- DefaultCache setting. -->
<defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" maxEntriesLocalDisk="100000"/>
</ehcache>
ehcache.xml
5、配置 Apache Shiro
①applicationContext-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <description>apache shiro配置</description> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/rest/page/login"/>
<property name="successUrl" value="/rest/index"/>
<property name="unauthorizedUrl" value="/rest/page/401"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
<!-- anon:它对应的过滤器里面是空的,什么都没做 -->
<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<property name="filterChainDefinitions">
<value>
<!-- 静态资源允许访问 -->
/app/** = anon
/hemi/** = anon
/assets/** = anon
<!-- 登录页允许访问 -->
/rest/user/login = anon
<!-- 其他资源需要认证 -->
/** = authc
</value>
</property>
</bean> <!-- 缓存管理器 使用Ehcache实现 -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean> <!-- 会话DAO -->
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/> <!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="sessionDAO" ref="sessionDAO"/>
</bean> <!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realms">
<list>
<ref bean="securityRealm"/>
</list>
</property>
<!-- cacheManager,集合spring缓存工厂 -->
<property name="cacheManager" ref="shiroEhcacheManager" />
<property name="sessionManager" ref="sessionManager" />
</bean> <!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>
applicationContext-shiro.xml
②ehcache-shiro.xml
<ehcache updateCheck="false" name="shiroCache"> <defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
ehcache-shiro.xml
6、配置 Mybatis
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="dialectClass" value="com.hemi.factor.core.feature.orm.dialect.MySql5Dialect"/>
</properties> <!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
<settings> <!-- 全局映射器启用缓存 -->
<setting name="cacheEnabled" value="true"/> <!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="true"/> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true"/> <!-- 允许使用列标签代替列名 -->
<setting name="useColumnLabel" value="true"/> <!-- 不允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
<setting name="useGeneratedKeys" value="false"/> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->
<setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE -->
<!-- <setting name="defaultExecutorType" value="BATCH" /> --> <!-- 数据库超过25000秒仍未响应则超时 -->
<!-- <setting name="defaultStatementTimeout" value="25000" /> --> <!-- Allows using RowBounds on nested statements -->
<setting name="safeRowBoundsEnabled" value="false"/> <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn. -->
<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT
local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. -->
<setting name="localCacheScope" value="SESSION"/> <!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values
like NULL, VARCHAR or OTHER. -->
<setting name="jdbcTypeForNull" value="OTHER"/> <!-- Specifies which Object's methods trigger a lazy load -->
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="false"/> </settings> <typeAliases>
<package name="com.hemi.factor.web.model"/>
<package name="com.hemi.factor.web.enums"/>
</typeAliases> <plugins>
<plugin interceptor="com.hemi.factor.core.feature.orm.mybatis.PaginationResultSetHandlerInterceptor"/>
<plugin interceptor="com.hemi.factor.core.feature.orm.mybatis.PaginationStatementHandlerInterceptor"/>
</plugins> </configuration>
mybatis-config.xml
7、配置Springmvc
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd "> <!-- 扫描controller(controller层注入) -->
<context:component-scan base-package="com.hemi.factor.web.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan> <!-- 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的 -->
<!-- 指定自己定义的validator -->
<!--<mvc:annotation-driven validator="validator"/>--> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> </bean>
<bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="webBindingInitializer"/>
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="fastjsonConverter" />
</list>
</property>
</bean>
<!--<!– 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册 –>-->
<!--<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">-->
<!--<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>-->
<!--<!– 如果不加默认到 使用classpath下的 ValidationMessages.properties –>-->
<!--<property name="validationMessageSource" ref="messageSource"/>-->
<!--</bean>--> <!--<!– 国际化的消息资源文件(本系统中主要用于显示/错误消息定制) –>-->
<!--<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">-->
<!--<property name="basenames">-->
<!--<list>-->
<!--<!– 在web环境中一定要定位到classpath 否则默认到当前web应用下找 –>-->
<!--<value>classpath:messages</value>-->
<!--<value>classpath:org/hibernate/validator/ValidationMessages</value>-->
<!--</list>-->
<!--</property>-->
<!--<property name="useCodeAsDefaultMessage" value="false"/>-->
<!--<property name="defaultEncoding" value="UTF-8"/>-->
<!--<property name="cacheSeconds" value="60"/>-->
<!--</bean>--> <mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
</mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="zh_CN"/>
</bean> <!-- 改动begin -->
<!-- 解析String请求数据 -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean> <!--<!– 解析json请求数据,将json转换为java对象 –>-->
<bean id="fastjsonConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="features">
<array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
<!-- 空值继续输出 -->
<value>WriteMapNullValue</value>
<!-- 防止循环引用 -->
<value>DisableCircularReferenceDetect</value>
<!-- 格式化日期,默认格式为:yyyy-MM-dd HH:mm:ss -->
<value>WriteDateUseDateFormat</value>
</array>
</property>
</bean>
<!-- 防止循环引用 -->
<bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property>
</bean> <!-- ContentNegotiatingViewResolver视图解析器,返回多视图 -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<!-- 这里是否忽略掉accept header,默认就是false -->
<property name="ignoreAcceptHeader" value="true" />
<!-- 启用参数支持 -->
<property name="favorParameter" value="false"/>
<!-- 启用扩展名支持 -->
<property name="favorPathExtension" value="true"/>
<!-- 如果所有的mediaType都没匹配上,就会使用defaultContentType -->
<property name="defaultContentType" value="text/html" /> <property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property> <property name="defaultViews">
<list>
<!-- json视图 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">
<property name="extractValueFromSingleKeyModel" value="true" />
<property name="features">
<array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
<!-- 空值继续输出 -->
<value>WriteMapNullValue</value>
<!-- 防止循环引用 -->
<value>DisableCircularReferenceDetect</value>
<!-- 格式化日期,默认格式为:yyyy-MM-dd HH:mm:ss -->
<value>WriteDateUseDateFormat</value>
</array>
</property>
</bean>
</list>
</property> <property name="viewResolvers">
<list>
<!-- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="contentType" value="text/html" />
<!-- 对模型视图添加前后缀 -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean> </list>
</property> </bean>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<mvc:default-servlet-handler/> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<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> <!--开启AOP,对类代理-->
<aop:config proxy-target-class="true"/>
<!-- 启用shrio授权注解拦截方式 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> </beans>
spring-mvc.xml
8、其他
①messages.properties
#user
user.username.null=用户名不能为空
user.password.null=密码不能为空
messages.properties
②log4j.properties
# DEBUG,INFO,WARN,ERROR,FATAL
LOG_LEVEL=INFO log4j.rootLogger=${LOG_LEVEL},CONSOLE,FILE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{8}@(%F:%L):%m%n
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{1}@(%F:%L):%m%n log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File=${catalina.base}/logs/factor.log
log4j.appender.FILE.Encoding=utf-8
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} %C{8}@(%F\:%L)\:%m%n
log4j.properties
③factor.sql
CREATE DATABASE factor; DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` bigint(20) NOT NULL COMMENT '主键',
`name` varchar(128) NOT NULL COMMENT '资源名称',
`type` varchar(32) NOT NULL COMMENT '资源类型:menu,button,',
`url` varchar(128) DEFAULT NULL COMMENT '访问url地址',
`percode` varchar(128) DEFAULT NULL COMMENT '权限代码字符串',
`parentid` bigint(20) DEFAULT NULL COMMENT '父结点id',
`parentids` varchar(128) DEFAULT NULL COMMENT '父结点id列表串',
`sortstring` varchar(128) DEFAULT NULL COMMENT '排序号',
`available` char(1) DEFAULT NULL COMMENT '是否可用,1:可用,0不可用',
`icon` varchar(128) DEFAULT NULL COMMENT '图标',
`style` varchar(128) DEFAULT NULL COMMENT '样式',
`obiligate` varchar(128) DEFAULT NULL COMMENT '预留字段',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES ('', '权限', '', '', 'user:create', '', '0/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '用户界面', 'menu', null, 'super_admin', null, null, null, null, 'fa fa-rss-square', null, null);
INSERT INTO `sys_permission` VALUES ('', '界面1', 'menu', null, 'user:create', '', '', null, null, null, null, null);
INSERT INTO `sys_permission` VALUES ('', '界面2', 'menu', null, 'user:create', '', '', null, null, null, null, null);
INSERT INTO `sys_permission` VALUES ('', '系统管理', 'menu', null, 'super_admin', null, null, null, null, 'fa fa-gears', null, null);
INSERT INTO `sys_permission` VALUES ('', '商品管理', 'menu', '/item/queryItem.action', 'user:create', '', '', '1.', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '用户管理', 'menu', '/user/query.action', 'super_admin', '', '', '2.', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '权限管理', 'menu', null, 'super_admin', '', '', null, null, null, null, null);
INSERT INTO `sys_permission` VALUES ('', '个人中心', 'menu', null, 'user:create', null, null, null, '', 'fa fa-user', null, null);
INSERT INTO `sys_permission` VALUES ('', '信息修改', 'menu', null, 'user:create', '', '', null, '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '密码修改', 'menu', null, 'user:create', '', '', null, null, null, null, null);
INSERT INTO `sys_permission` VALUES ('', '商品新增', 'permission', '/item/add.action', 'item:create', '', '0/1/11/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '商品修改', 'permission', '/item/editItem.action', 'item:update', '', '0/1/11/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '商品删除', 'permission', '', 'item:delete', '', '0/1/11/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '商品查询', 'permission', '/item/queryItem.action', 'item:query', '', '0/1/15/', null, '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '用户新增', 'permission', '', 'user:create', '', '0/1/21/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '用户修改', 'permission', '', 'user:update', '', '0/1/21/', '', '', null, null, null);
INSERT INTO `sys_permission` VALUES ('', '用户删除', 'permission', '', 'user:delete', '', '0/1/21/', '', '', null, null, null); -- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` varchar(36) NOT NULL,
`name` varchar(128) NOT NULL,
`available` char(1) DEFAULT NULL COMMENT '是否可用,1:可用,0不可用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('admin', '管理员', '');
INSERT INTO `sys_role` VALUES ('superadmin', '超级管理员', '');
INSERT INTO `sys_role` VALUES ('user', '普通用户', '');
INSERT INTO `sys_role` VALUES ('vipuser', 'VIP用户', ''); -- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`id` varchar(36) NOT NULL,
`sys_role_id` varchar(32) NOT NULL COMMENT '角色id',
`sys_permission_id` varchar(32) NOT NULL COMMENT '权限id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES ('rp01', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp02', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp03', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp04', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp05', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp06', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp07', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp08', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp09', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp10', 'admin', '');
INSERT INTO `sys_role_permission` VALUES ('rp11', 'user', '');
INSERT INTO `sys_role_permission` VALUES ('rp12', 'user', '');
INSERT INTO `sys_role_permission` VALUES ('rp13', 'user', '');
INSERT INTO `sys_role_permission` VALUES ('rp14', 'user', '');
INSERT INTO `sys_role_permission` VALUES ('rp15', 'user', '');
INSERT INTO `sys_role_permission` VALUES ('rp16', 'user', ''); -- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` varchar(36) NOT NULL COMMENT '主键',
`usercode` varchar(32) NOT NULL COMMENT '账号',
`username` varchar(64) NOT NULL COMMENT '姓名',
`password` varchar(32) NOT NULL COMMENT '密码',
`salt` varchar(64) DEFAULT NULL COMMENT '盐',
`locked` char(1) DEFAULT NULL COMMENT '账号是否锁定,1:锁定,0未锁定',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('ua01', 'admin', '佟掌柜', '', 'uiwueylm', '');
INSERT INTO `sys_user` VALUES ('ut01', 'user', '小鱼儿', '', 'sdfafd', ''); -- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` varchar(36) NOT NULL,
`sys_user_id` varchar(32) NOT NULL,
`sys_role_id` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('ur01', 'ua01', 'admin');
INSERT INTO `sys_user_role` VALUES ('ur02', 'ut01', 'user');
factor.sql
THE END.