1. 程式人生 > >ssm+Apache shiro--配置文件

ssm+Apache shiro--配置文件

target 驗證 resource resolv 有效 like user auto xmlns

1,web.xml

  

<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- 添加contextConfigLocation,通知Spring到classpath下找applicationContext配置文件,否則默認到web-info下 -->
	<context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:applicationContext.xml</param-value>  
    </context-param>
     
	<servlet>
		<servlet-name>IMDispatchServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>IMDispatchServlet</servlet-name>
		<!-- 默認匹配所有請求 -->
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	<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>*.do</url-pattern>
		<dispatcher>REQUEST</dispatcher>
   		<dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
	</filter-mapping>
     <!-- 防止spring內存溢出監聽器 -->  <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <!-- 配置錯誤頁--> <error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page>     <error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- 默認頁面 --> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>

2,配置文件分為applicationContext.xml,spring-shiro.mxl,spring-mybatis.xml,encache-shiro.xml

applicationContext.xml配置spring mvc等內容:

  

<!-- spring mvc 配置 -->
    <mvc:annotation-driven />
    
    <mvc:default-servlet-handler/>
<!-- 配置靜態資源映射
<mvc:resources location="/assets/" mapping="/assets/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> --> <!-- viewResolver配置 --> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 掃描web相關 --> <context:component-scan base-package
="com.test.controller"></context:component-scan> <!--文件上傳下載相關--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="50000"></property> <property name="maxInMemorySize" value="4096"></property> </bean> <!--攔截器配置--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/>
       <!--不進行攔截的連接--> <mvc:exclude-mapping path="/common/login.do*"/> <bean class="com.test.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="/error.jsp"></property> </bean> <import resource="classpath:spring-mybatis.xml"/> <import resource="classpath:spring-shiro.xml"/> </beans>

spring-mybatis.xml配置文件內容;

  

<util:properties id="jdbc" location="classpath:jdbc.properties" />
    
    <context:component-scan base-package="com.test.service.impl" />
    <!-- Hikari Datasource使用-->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"  destroy-method="shutdown">
        <property name="jdbcUrl" value="#{jdbc.adminUrl}" />
        <property name="driverClassName" value="#{jdbc.adminDriver}" />
        <property name="username" value="#{jdbc.adminUser}" />
        <property name="password" value="#{jdbc.adminPassword}" />
        <!-- 連接只讀數據庫時配置為true, 保證安全 -->  
         <property name="readOnly" value="false" />
         <!-- 等待連接池分配連接的最大時長(毫秒),超過這個時長還沒可用的連接則發生SQLException, 缺省:30秒 -->  
         <property name="connectionTimeout" value="30000" />  
         <!-- 一個連接idle狀態的最大時長(毫秒),超時則被釋放(retired),缺省:10分鐘 -->  
         <property name="idleTimeout" value="600000" />
         <!-- 一個連接的生命時長(毫秒),超時而且沒被使用則被釋放(retired),缺省:30分鐘,建議設置比數據庫超時時長少30秒,參考MySQL wait_timeout參數(show variables like ‘%timeout%‘;) -->  
         <property name="maxLifetime" value="1800000" /> 
         <property name="maximumPoolSize" value="50" /> 
    </bean>
    <!-- sqlSessionFactory會化工廠配置 -->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 註入連接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置mysql全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-configuration.xml" />
        <!-- 掃描entity包,使用別名 -->
        <!-- <property name="typeAliasesPackage" value="com.test.entity"/> -->
        <!-- 掃面sql配置文件 mapper文件 -->
        <property name="mapperLocations" value="classpath:com/test/mapper/*.xml" />
    </bean>

    <!-- 掃面dao接口包 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"></property>
    </bean>

    <!-- 配置事務 -->
    <bean id="TxManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置基於註解的聲明式事務 ,使用註解管理 1,明確編程風格 2,保證事務方法執行時間盡可能短 3,不穿插其他網路操作 4,有些寫入操作不需要事務,只讀只寫寫入一條數據,刪除,更一個數據時,如果是批量操作則需要。 -->
    <tx:annotation-driven transaction-manager="TxManager" proxy-target-class="true"/>

    <tx:advice id="IMAdvice" transaction-manager="TxManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true" />
            <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
            <tx:method name="update*" propagation="REQUIRED"
                rollback-for="java.lang.Exception" />
            <tx:method name="delete*" propagation="REQUIRED"
                rollback-for="java.lang.Exception" />
        </tx:attributes>
    </tx:advice>
    <aop:config proxy-target-class="true">
        <aop:advisor advice-ref="IMAdvice"
            pointcut="within(com.test.service.impl..*)" />
    </aop:config>

spring-shiro.xml配置內容:

<!-- 配置自定義Realm -->
    <bean id="myRealm" class="com.test.MyRealm">
        <property name="authorizationCacheName" value="myShiroCache"/>
    </bean>
    
    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
         <!-- cache  -->
        <property name="cacheManager" ref="cacheManager"></property>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>
    
    <!-- Session Manager -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- 相隔多久檢查一次session的有效性   -->
         <property name="sessionValidationInterval" value="1800000"/>  
          <!-- session 有效時間為半小時 (毫秒單位)-->  
       <property name="globalSessionTimeout" value="1800000"/>
       <property name="sessionDAO" ref="sessionDAO"/>
       <!-- session 監聽,可以多個。 -->
       <property name="sessionListeners">
           <list>
               <ref bean="customSessionListener"/>
           </list>
       </property>
       <!-- 間隔多少時間檢查,不配置是60分鐘 -->    
      <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
      <!-- 是否開啟 檢測,默認開啟 -->
      <property name="sessionValidationSchedulerEnabled" value="true"/>
       <!-- 是否刪除無效的,默認也是開啟 -->
      <property name="deleteInvalidSessions" value="true"/>
        <!-- 會話Cookie模板 -->
       <property name="sessionIdCookie" ref="sessionIdCookie"/>
       <property name="sessionIdCookieEnabled" value="true"/>
    </bean>
    <!-- 會話驗證調度器 -->
    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
         <!-- 間隔多少時間檢查,不配置是60分鐘 -->
         <property name="interval" value="12000000"/>
         <property name="sessionManager" ref="sessionManager"/>
    </bean>
    <!-- 會話DAO -->
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="activeSessionCache"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
    </bean>
    <bean id="customSessionListener" class="com.test.MySessionManager"></bean>
    <!-- cookie 模板 -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg name="name"  value="IMSID"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="1800"/><!-- 單位S-->
    </bean>
    <!-- 會話ID生成器  -->
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!-- Shiro過濾器 核心-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,這個屬性是必須的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- 權限認證失敗,則跳轉到指定頁面 -->
        <property name="unauthorizedUrl" value="/error.jsp"/>
        <!-- Shiro連接約束配置,即過濾鏈的定義 -->
        <property name="filterChainDefinitions">
            <value>
                <!--anon 表示匿名訪問,不需要認證以及授權-->
                /common**=anon
                <!--authc表示需要認證 沒有進行身份認證是不能進行訪問的-->
               /user**=authc
            </value>
        </property>
        
    </bean>
    <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 開啟Shiro註解 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
   

encache-shiro.xml緩存配置:

<ehcache updateCheck="false" name="shiroCache">
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
    />
    
<!--myrealm 配置認證授權緩存的名字,顯式指定-->
    <cache name="myShiroCache"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="30"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120"/>
</ehcache>

 

ssm+Apache shiro--配置文件