Spring SpringMvc Hibernate Shiro 整合配置
application.properties 配置文件所引用的变量
#mysql jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.5.230:3306/project?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=dcsoft123 #connection pool settings jdbc.pool.maxIdle=5 jdbc.pool.maxActive=40 #hibernate settings hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.search.default.indexBase=indexes hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory #cache settings hibernate.ehcache.configFile=cache/ehcache-hibernate-local.xml #admin path adminPath=/admin #front path frontPath=/front
Spring配置文件 applicationContext.xml
<?xml version="1.1" 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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.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 http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd" default-lazy-init="true"> <description>Spring公共配置 </description> <!-- 读取配置文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath*:/application.properties" /> <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 --> <context:component-scan base-package="com.project"> </context:component-scan> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <!-- 定义Hibernate Session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.cache.use_second_level_cache">false</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="net.sf.ehcache.configurationResourceName">${hibernate.ehcache.configFile}</prop> </props> </property> <property name="packagesToScan" value="com.projcet" /><!-- 如果多个,用“,”分隔 --> </bean> <!-- 定义事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 配置 JSR303 Bean Validator 定义 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> <!-- 数据源配置, 使用druid连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <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="filters" value="mergeStat" /> <!-- 密码解密 --> <!-- <property name="filters" value="config" /> <property name="connectionProperties" value="config.decrypt=true" /> --> <!-- 申请连接的时候检测 --> <property name="testWhileIdle" value="true"></property> <!-- 检测连接 --> <property name="validationQuery" value="select 'x'"></property> <!--maxActive: 最大连接数量 --> <property name="maxActive" value="${jdbc.pool.maxActive}" /> <!--initialSize: 初始化连接 --> <property name="initialSize" value="${jdbc.pool.maxIdle}" /> </bean> </beans>
Web.xml
<?xml version="1.1" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>projcet</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/applicationContext.xml, classpath*:/applicationContext-shiro.xml, </param-value> </context-param> <context-param> <param-name>spring.profiles.default</param-name> <param-value>production</param-value> </context-param> <!--spring ApplicationContext 载入 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Filter 定义 --> <!-- 编码 filter --> <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> <!-- Hibernate Open Session In View filter 允许在事务提交之后延迟加载显示所需要的对象。--> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- ajax filter 自定义filter 跨域访问用的--> <filter> <filter-name>ajaxFilter</filter-name> <filter-class>com.project.system.utils.AjaxFilter</filter-class> </filter> <filter-mapping> <filter-name>ajaxFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- shiro filter --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <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 springMVC 前端控制器--> <servlet> <servlet-name>springServlet</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>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- druid 监控 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- <servlet> <display-name>HighChartsUtil</display-name> <servlet-name>HighChartsUtil</servlet-name> <servlet-class>com.esailcar.finance.common.utils.HighChartsUtil</servlet-class> </servlet> <servlet-mapping> <servlet-name>HighChartsUtil</servlet-name> <url-pattern>/HighChartsUtil</url-pattern> </servlet-mapping> --> <!-- kaptcha验证码 --> <servlet> <servlet-name>kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>kaptcha</servlet-name> <url-pattern>/static/images/kaptcha.jpg</url-pattern> </servlet-mapping> <!-- session过期时间 --> <session-config> <session-timeout>20</session-timeout> </session-config> <!-- 错误页面设置 --> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/WEB-INF/views/error/403.jsp</location> </error-page> </web-app>
shiro配置文件 applicationContext-shiro.xml
<?xml version="1.1" 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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" default-lazy-init="true"> <description>Shiro安全配置</description> <!-- 读取配置文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath*:/application.properties" /> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 自定义Realm --> <bean id="userRealm" class="com.projcet.system.service.UserRealm" /> <!-- 缓存管理:用户授权信息Cache, 采用EhCache --> <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:cache/ehcache-shiro.xml"/> </bean> <!-- Shiro安全管理器 :Shiro的主要业务层对象基于web的应用程序 ref是对应的配置或者类名,--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="userRealm" /> <property name="cacheManager" ref="shiroEhcacheManager" /> </bean> <!-- 自定义验证码Filter--> <!-- <bean id="myCaptchaFilter" class="com.project.system.utils.FormAuthenticationCaptchaFilter"/> --> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager" /> <!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 --> <property name="loginUrl" value="${adminPath}/login" /> <!-- 登录成功后要跳转的连接--> <property name="successUrl" value="${adminPath}" /> <!-- 用户访问未对其授权的资源时,所显示的连接 --> <!-- <property name="unauthorizedUrl" value="/"></property> --> <!-- <property name="filters"> <map> <entry key="authc" value-ref="myCaptchaFilter"/> </map> </property> --> <!-- "anon"访问是不需要认证控制的,主要是用于用户登录和退出 --> <!-- "authc"访问是需要认证控制的,就是说只有通过认证的用户才可以访问该资源。如果用户直接在地址栏中,系统会自动跳转至登录页面,要求用户先进行身份认证 --> <property name="filterChainDefinitions"> <value> /static/** = anon ${adminPath}/login = authc ${adminPath}/** = user /rest/**=authcBasic </value> </property> </bean> <!-- AOP式方法级权限检查:开启Shiro的注解(如@RequiresRoles,@RequiresPermissions), 需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans>
自定义UserRealm 继承 AuthorizingRealm 用于身份认证和授权
package com.projcet.system.service; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.stereotype.Service;
@Service public class UserRealm extends AuthorizingRealm { @Override
//授权回调函数 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println("AuthorizationInfo"); // TODO Auto-generated method stub return null; } @Override
//身份认证回调函数 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException { // TODO Auto-generated method stub System.out.println("AuthenticationInfo"); return null; } }
SpringMVC 配置文件 spring-mvc.xml
<?xml version="1.1" 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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.projcet"/> <!-- 自动注册AdapterMapping HandlerMapping --> <mvc:annotation-driven></mvc:annotation-driven> <!--视图解析器 定义JSP文件的位置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 容器默认的DefaultServletHandler处理 所有静态内容与无RequestMapping处理的URL --> <mvc:default-servlet-handler /> <!-- 定义无需Controller的url<->view直接映射 --> <mvc:view-controller path="/admin" view-name="/system/index" /> <!-- 将Controller抛出的异常转到特定View--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop> <prop key="java.lang.Throwable">error/500</prop> </props> </property> </bean> </beans>
hibernate cache配置 :
<?xml version="1.1" encoding="UTF-8"?> <ehcache updateCheck="false" name="hibernateCache"> <!-- DefaultCache setting. --> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="false" maxEntriesLocalDisk="100000" memoryStoreEvictionPolicy="LFU" /> </ehcache>
shiro cache配置:
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>

浙公网安备 33010602011771号