shiro 与spring的集成

时间:2022-09-24 18:17:56

1.导入spring与shiro的jar包

2.在web.xml 文件中配置shiro的shiroFilter

<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
  <!-- 表示bean的生命周期由servlet管理 -->
  <param-name>targetFilterLifecycle</param-name>
  <param-value>true</param-value>
</init-param>
<init-param>
  <param-name>targetBeanName</param-name>
  <param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

3.在applicationContext.xml 文件中配置SecurityManager和Realm

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <property name="securityManager" ref="securityManager"/>
  <property name="loginUrl" value="/login.jsp"/>
  <property name="unauthorizedUrl" value="/login.jsp"/>
  <!-- shiro 的过滤器执行链 -->
  <property name="filterChainDefinitions">
    <value>
      /login.jsp = anon
      /user/login.do = anon
      /user/logout.do = logout
      /** = authc
    </value>
  </property>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="userRealm"/>
    <property name="sessionManager" ref="sessionManager"/>

      <property name="rememberMeManager" ref="rememberMeManager"/>
</bean>

<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
  <property name="cookie" ref="rememberMeCookie"/>
</bean>

<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">

  <!-- 设置cookie的存活时间  -->
  <property name="maxAge" value="604800"/>

  <!-- 设置cookie的名称 -->
  <property name="name" value="rememberMe"/>

</bean>

<bean id="userRealm" class="com.edu.aynu.oalist.beans.Relam">
</bean>
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
  <property name="globalSessionTimeout" value="300000"/>
  <property name="deleteInvalidSession" value="true"></property>
</bean>