基于自己的一个小项目重新搭建了一次开发环境(Maven+SSH+JPA+Shiro),借此说说这些框架的整合过程。
1.基本概念
1.1 Spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
1.2 Spring MVC
Spring MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring MVC 也是简化我们日常Web开发的。
1.3 Hibernate
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJBd的J2EE 架构中取代CMP,完成数据持久化 的重任。1.4 Maven
Maven是基于项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具。
1.5 Apache Shiro
Shiro是一个用Java语言事项的框架,提供了一个可用的安全性框架,目的是通过简单易用的API提供身份验证和授权。2.配置
2.1 Spring配置
2.1.1引入Spring的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
2.1.2加入Spring的配置文件
1.添加配置文件:spring-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<!--开启注解 -->
<context:annotation-config />
<!-- 导入资源文件 定义受环境影响易变的变量 -->
<bean 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:*.properties</value>
</list>
</property>
</bean>
</beans>
2.在web.xml中配置启动Spring IOC容器的监听器
<?xml version="1.0" encoding="UTF-8"?>
<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>fresh troops web server</display-name>
<!-- 配置启动Spring IOC容器的Listener -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:META-INF/spring/spring*.xml
</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index/index</welcome-file>
</welcome-file-list>
</web-app>
2.1.3 说明
1.Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。对于扫描到的组件,Spring有默认的命名策略:使用非限定类名,第一个字母小写.也可以在注解中通过value属性标识组件的名称。特定组件包括:
2.配置中是引入多个properties文件,如果只有一个properties,则可以这样写:
<context:property-placeholder location="classpath:application.properties"/>
3.启动对@AspectJ注解(切点类)的支持,可以添加以下配置:
<!-- 启动对@AspectJ注解的支持:自动为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy/>
4.在web.xml中,通常增加以下配置:
<!-- 可以使用RequestContextHolder.currentRequestAttributes() 获取到请求的attr -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- Spring 刷新Introspector防止内存泄露 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
2.2 Spring整合Hibernate
2.2.1整合什么
1.由IOC容器来生成hibernate的SessionFactory
2.让Hibernate/JPA使用上Spring的声明式事务
2.2.2步骤
1.加入hibernate的jar包(由于用到了druid的连接池,同时需要引入对应的jar包)
<!-- ORM Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!-- JDBC Datasource -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.16</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置hibernate的基本属性 -->
<!-- 1.数据源需配置到IOC容器中,所以在此处不再需要配置数据源 -->
<!-- 2.关联的.hbm.xml也在IOC容器 配置SessionFactory实例时再进行配置 -->
<!-- 3.配置hibernate的基本属性:方言,SQL显示及格式化,生成数据 -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<!-- 设置自动建表类型 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--设置外连接抓取树的最大深度 -->
<property name="hibernate.max_fetch_depth">3</property>
<property name="hibernate.jdbc.fetch_size">100</property>
<property name="hibernate.jdbc.batch_size">30</property>
<!-- 设置Hibernate的事务隔离级别,MYSQL默认级别是4(在执行refresh时,取不到最新数据),SQLServer默认级别是2 -->
<property name="hibernate.connection.isolation">2</property>
<!-- 配置hibernate 二级缓存相关的属性 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
</session-factory>
</hibernate-configuration>
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 驱动名称 -->
<property name="driverClassName" value="${jdbc.driverClass}" />
<!-- JDBC连接串 -->
<property name="url" value="${jdbc.jdbcUrl}" />
<!-- 数据库用户名称 -->
<property name="username" value="${jdbc.user}" />
<!-- 数据库密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="${jdbc.maxPoolSize}" />
<!-- 初始化大小 -->
<property name="initialSize" value="${jdbc.initPoolSize}" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${jdbc.maxWait}" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${jdbc.minIdle}" />
<!-- 逐出连接的检测时间间隔 -->
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
<!-- 最小逐出时间 -->
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 开启Druid的监控统计功能 -->
<property name="filters" value="stat" />
<!-- 测试有效用的SQL Query
<property name="validationQuery" value="SELECT 'x'" /> -->
<!-- 连接空闲时测试是否有效 -->
<property name="testWhileIdle" value="true" />
<!-- 获取连接时测试是否有效 -->
<property name="testOnBorrow" value="false" />
<!-- 归还连接时是否测试有效 -->
<property name="testOnReturn" value="false" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan"></property>
<property name=""></property>
<property name="hibernateProperties">
<props>
<!--设置外连接抓取树的最大深度 -->
<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<!-- 自动建表类型 validate|create|create-drop|update -->
<!-- <prop key="hibernate.hbm2ddl.auto">validate</prop> -->
<!-- 是否显示SQL -->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!-- 显示SQL是否格式化 -->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!-- 设置Hibernate的事务隔离级别,MYSQL默认级别是4(在执行refresh时,取不到最新数据),SQLServer默认级别是2
READ UNCOMMITED:1
READ COMMITED:2
REPEATABLE READ:4
SERIALIZEABLE:8
-->
<prop key="hibernate.connection.isolation">${hibernate.connection.isolation}</prop>
<!-- 关闭二级缓存 -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<!-- 关闭实体字段映射校验 -->
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
<!-- 开启注解事务支持 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<!-- 配置Spring的声明式事务 -->
<!-- 1.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<qualifier value="mssqlEM"/>
</bean>
<!-- 2.配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"
no-rollback-for="java.lang.RuntimeException" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="create*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 3.配置事务切点,并把事务切点和事务属性关联起来 -->
<aop:config>
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.ft..service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
</beans>
4.在web.xml中增加Hibernate Session filter:
配置spring管理OpenSessionInViewFilter,来将一个session与一次完整的请求过程对应的线程相绑定。在Java Web项目中使用Hibernate经常会遇到LazyInitializationException。这是因为controller和model层(java代码)将通过JPA的一些启用了延迟加载功能的领域(如用getRefrence()方法或者在关联关系中采用fetch=FetchType.LAZY)返回给view层(jsp代码)的时候,由于加载领域对象的JPA Session已经关闭,导致这些延迟加载的数据访问异常。 <filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>这个sessionFactory是Spring配置文件中配置的bean
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.2.3说明
1.数据源配置在IOC容器中,即在Spring的配置文件中配置
2.关联的.hbm.xml配置在IOC容器中,如果采用的是注解,通过SessionFactory的packagesToScan属性配置
3.配置Spring的事务
2.3 Spring整合Hibernate JPA
<!-- Spring集成Hibernate JPA -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<!-- 配置数据源 参考:http://blog.csdn.net/weir2008/article/details/42521347
如果需要配置多个数据源,可以区分 命名,例如:mssqlDataSource。
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 驱动名称 -->
<property name="driverClassName" value="${jdbc.driverClass}" />
<!-- JDBC连接串 -->
<property name="url" value="${jdbc.jdbcUrl}" />
<!-- 数据库用户名称 -->
<property name="username" value="${jdbc.user}" />
<!-- 数据库密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="${jdbc.maxPoolSize}" />
<!-- 初始化大小 -->
<property name="initialSize" value="${jdbc.initPoolSize}" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${jdbc.maxWait}" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${jdbc.minIdle}" />
<!-- 逐出连接的检测时间间隔 -->
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
<!-- 最小逐出时间 -->
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 开启Druid的监控统计功能 -->
<property name="filters" value="stat" />
<!-- 测试有效用的SQL Query
<property name="validationQuery" value="SELECT 'x'" /> -->
<!-- 连接空闲时测试是否有效 -->
<property name="testWhileIdle" value="true" />
<!-- 获取连接时测试是否有效 -->
<property name="testOnBorrow" value="false" />
<!-- 归还连接时是否测试有效 -->
<property name="testOnReturn" value="false" />
</bean>
<!-- 整合jpa -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="com.ft"></property>
<property name="persistenceUnitName" value="mssqldb"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
</bean>
</property>
<property name="jpaProperties">
<props>
<!--设置外连接抓取树的最大深度 -->
<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<!-- 自动建表类型 validate|create|create-drop|update -->
<!-- <prop key="hibernate.hbm2ddl.auto">validate</prop> -->
<!-- 是否显示SQL -->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!-- 显示SQL是否格式化 -->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!-- 设置Hibernate的事务隔离级别,MYSQL默认级别是4(在执行refresh时,取不到最新数据),SQLServer默认级别是2
READ UNCOMMITED:1
READ COMMITED:2
REPEATABLE READ:4
SERIALIZEABLE:8
-->
<prop key="hibernate.connection.isolation">${hibernate.connection.isolation}</prop>
<!-- 关闭二级缓存 -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<!-- 关闭实体字段映射校验 -->
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
<!-- 开启注解事务支持 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<!-- 配置Spring的声明式事务 -->
<!-- 1.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<qualifier value="mssqlEM"/>
</bean>
<!-- 2.配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"
no-rollback-for="java.lang.RuntimeException" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="create*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 3.配置事务切点,并把事务切点和事务属性关联起来 -->
<aop:config>
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.ft..service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
<!-- 4.配置repositories自动代理功能,在 Spring 配置文件中启用扫描并自动创建代理的功能 -->
<jpa:repositories base-package="com.ft"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>
</beans>
5.在web.xml中将Hibernate Session filter该为EntityManager Filter
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value><!-- 这个entityManagerFactory是Spring配置文件中配置的bean -->
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.4 Spring整合MVC
2.4.1整合什么
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了
控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
2.4.2步骤
1.引入Spring MVC的jar包:
<!-- Spring Web MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.release</version>
</dependency>
2.添加Spring MVC配置文件: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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 配置自动扫描的包:主要扫描Controller和ControllerAdvice -->
<context:component-scan base-package="com.ft"
use-default-filters="false">
<!-- 扫描符合@Controller和@ControllerAdvice的类 -->
<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>
<!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
它会对进入 DispatcherServlet 的请求进行筛查,如果发现是没有经过映射的请求,就将该请求交由 WEB 应用服务器默认的 Servlet
处理,如果不是静态资源的请求,才由DispatcherServlet 继续处理。 一般 WEB 应用服务器默认的 Servlet 的名称都是 default。若所使用的
WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 -->
<mvc:default-servlet-handler />
<!-- 静态资源映射 -->
<mvc:resources mapping="/webui/**" location="/webui/" />
<!-- 配置直接转发的页面 ,可以直接响应转发的页面,而无需再经过Handler的方法 但是出现问题:以前配置的的controller都不起作用了。
解决方法:配置mvc:annotation-driven -->
<!-- <mvc:view-controller path="/" view-name="index"/> -->
<!-- 在实际开发中通常都需要配置mvc:annotation-driven标签 -->
<mvc:annotation-driven/>
<!-- 文件上传配置注意:这里申明的id必须为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
<!-- 用于使用@ResponseBody后返回中文避免乱码-->
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json;charset=UTF-8" />
</bean> -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<!-- <value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/msexcel;charset=UTF-8</value> -->
</list>
</property>
<property name="writeAcceptCharset" value="false" /><!-- 用于避免响应头过大 -->
</bean>
</list>
</property>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/error_fileupload.jsp页面 -->
<prop
key="org.springframework.web.multipart.MaxUploadSizeExceededException">WEB-INF/error_fileupload</prop>
<!-- 处理其它异常(包括Controller抛出的) -->
<prop key="java.lang.Throwable">WEB-INF/500</prop>
</props>
</property>
</bean>
</beans>
3.在web.xml中配置Spring DispatcherServlet
<!-- Spring MVC:配置Spring DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.4.3说明
1.在spring-mvc.xml配置文件中,配置扫描包,这与spring-context.xml文件中扫描包配置重复,会报错。而且在Spring中通常配置扫描除标注Controller以外的类,而Spring MVC则只扫描标注Controller的类,所以在spring-mvc.xml配置增加了只扫描标注Controller的类。此时需要在spring-context.xml的扫描包配置中增加过滤标注Controller的类
<!--开启注解 -->
<context:annotation-config />
<!--扫描包:除@Controller*注解以外的类 -->
<context:component-scan base-package="com.ft" >
<!-- 扫描符合除@Controller注解以外的类 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
2.在web.xml中,配置servlet编码过滤器
<!-- Spring MVC:配置servlet编码过滤器 -->
<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>
<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>
2.5 Spring整合Shiro
2.5.1整合什么
2.5.2步骤
<!-- Shiro 权限管理框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
package com.ft.security.shiro.realm;
import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.ft.security.entity.ACL;
import com.ft.security.entity.Role;
import com.ft.security.entity.User;
import com.ft.security.service.ACLService;
import com.ft.security.service.RoleService;
import com.ft.security.service.UserService;
import com.ft.security.shiro.authc.UsernamePasswordVerificationCodeToken;
public class UserRealm extends AuthorizingRealm{
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private ACLService aclService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String currentLoginName = (String)principals.getPrimaryPrincipal();
List<String> roles = new ArrayList<String>();
List<String> permissions = new ArrayList<String>();
//从数据库中获取当前登录用户的详细信息
if(null != currentLoginName){
//获取当前用户下所有ACL权限列表
List<ACL> acls = aclService.findByUser(currentLoginName);
for (int i = 0; i < acls.size(); i++) {
permissions.add(acls.get(i).getCode());
}
//获取当前用户下拥有的所有角色列表
List<Role> roles2 = roleService.findByUser(currentLoginName);
for (int i = 0; i < roles2.size(); i++) {
roles.add(roles2.get(i).getCode());
}
}else{
throw new AuthorizationException();
}
System.out.println("#######获取角色:"+roles);
System.out.println("#######获取权限:"+permissions);
//为当前用户设置角色和权限
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roles);
authorizationInfo.addStringPermissions(permissions);
return authorizationInfo;
}
/**
* 验证当前登录的Subject
* LoginController.login()方法中执行Subject.login()时 执行此方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
System.out.println("###【开始认证[SessionId]】"+SecurityUtils.getSubject().getSession().getId());
UsernamePasswordVerificationCodeToken token = (UsernamePasswordVerificationCodeToken)authcToken;
String loginName = (String)token.getPrincipal();
User user = userService.findByLoginName(loginName);
if(user == null) {
throw new UnknownAccountException();//没找到帐号
}
if(user.getStatus()==0) {
throw new LockedAccountException(); //帐号锁定
}
if(user.getStatus()==-1) {
throw new DisabledAccountException();//账号禁用
}
//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getLoginName(), //用户名
user.getLoginPassword(), //密码
ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
}
3..添加Spring Shiro配置文件: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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的 继承 AuthorizingRealm -->
<bean id="userRealm" class="com.ft.security.shiro.realm.UserRealm" />
<!-- 安全管理器
Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session
即<property name="sessionMode" value="native"/>,详细说明见官方文档
这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替
-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
<bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/index" />
</bean>
<!-- 基于Form表单的身份验证过滤器 -->
<bean id="custormFormAuthenticationFilter" class="com.ft.security.shiro.web.filter.authc.CustomFormAuthenticationFilter">
<property name="usernameParam" value="loginName"/>
<property name="passwordParam" value="loginPassword"/>
<property name="rememberMeParam" value="rememberMe"/>
<property name="failureKeyAttribute" value="shiroLoginFailure" />
</bean>
<!-- Shiro的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/login"/>
<!-- 登录成功后要跳转的连接(也可以根据实际要求登录后登录到被拒绝的页面,登录成功后的处理逻辑可以在LoginController里编写) -->
<!-- <property name="successUrl" value="/login" /> -->
<!-- 用户访问未对其授权的资源时,所显示的连接(此配置 要求登录) -->
<property name="unauthorizedUrl" value="/login" />
<!-- Shiro过滤器的定义 -->
<property name="filters">
<util:map>
<entry key="authc" value-ref="custormFormAuthenticationFilter"></entry>
</util:map>
</property>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
<!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
/webui/** = anon
/login = authc
/logout = logout
/authenticated = authc
/** = authc
<!-- perms[user:query]表示访问此链接需要权限为user:query的用户 -->
/user = perms[user:query]
<!-- roles[manager]表示访问此链接需要用户的角色为manager -->
/user/edit/** = roles[SUPER_ADMIN],roles[COMM_ADMIN]
/user/del/** = roles[SUPER_ADMIN],roles[COMM_ADMIN]
<!-- 如果想实现所有请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,未登录验证则跳到/login,则通过如下配置:
/** = authc
-->
</value>
</property>
</bean>
<!-- Shiro生命周期处理器-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<!-- 开启Shiro Spring AOP 权限注解的支持
开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
-->
<aop:config proxy-target-class="true"></aop:config>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
4.在web.xml中增加一下配置:
<!--spring 集成 shiro 安全过滤器 通常放在最前面 -->
<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>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
2.5.3说明
3.实例
package com.ft.security.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.ft.security.entity.User;
import com.ft.security.service.PasswordHelper;
import com.ft.security.service.UserService;
import com.ft.security.verification.code.exception.VerificationCodeException;
import com.ft.util.SessionUtil;
import com.ft.web.vo.ValidatorJSON;
import com.ft.web.vo.ValidatorJSON.Json;
@Controller
public class SecurityController {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private UserService userService;
@Autowired
private PasswordHelper passwordHelper;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage() {
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
System.out.println("用户[" + currentUser.getPrincipal().toString() + "]已登录");
// 跳到首页
return "redirect:/";
}
return "login/login_h5";
}
/**
* 用户登录
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Json showLoginForm(HttpServletRequest req, Model model) {
String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
String error = null;
if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
error = "登录失败次数过多,账号锁定10分钟";
} else if(exceptionClassName != null) {
error = "其他错误:" + exceptionClassName;
}
if(error==null){
return ValidatorJSON.OK("/index");
}else{
model.addAttribute("error", error);
return ValidatorJSON.FAIL(1,error);
}
}
/**
* 用户登出
* no user proxy by shiro filter
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest request) {
SecurityUtils.getSubject().logout();
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/index";
}
}
创建登录jsp时,需要注意点,页面中用户名和密码的域名,需要和custormFormAuthenticationFilter中配置的对应属性的value一致。