一、web.xml文件的配置css
<?xml version="1.0" encoding="UTF-8"?> <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"> <!-- Web容器加載順序ServletContext--context-param--listener--filter--servlet --> <!-- 指定Spring的配置文件 --> <!-- 不然Spring會默認從WEB-INF下尋找配置文件,contextConfigLocation屬性是Spring內部固定的 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-context*.xml</param-value> </context-param> <!-- 防止發生java.beans.Introspector內存泄露,應將它配置在ContextLoaderListener的前面 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 實例化Spring容器 --> <!-- 應用啓動時,該監聽器被執行,它會讀取Spring相關配置文件,其默認會到WEB-INF中查找applicationContext.xml --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解決亂碼問題 --> <!-- forceEncoding默認爲false,此時效果可大體理解爲request.setCharacterEncoding("UTF-8") --> <!-- forceEncoding=true後,可大體理解爲request.setCharacterEncoding("UTF-8")和response.setCharacterEncoding("UTF-8") --> <filter> <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置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> <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> <!-- SpringMVC核心分發器 --> <servlet> <servlet-name>SpringMVC</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> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Session超時30分鐘(零或負數表示會話永不超時)--> <!-- <session-config> <session-timeout>30</session-timeout> </session-config> --> <!-- 默認歡迎頁 --> <!-- Servlet2.5中可直接在此處執行Servlet應用,如<welcome-file>servlet/InitSystemParamServlet</welcome-file> --> <!-- 這裏使用了SpringMVC提供的<mvc:view-controller>標籤,實現了首頁隱藏的目的,詳見applicationContext.xml --> <!-- <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> --> <error-page> <error-code>405</error-code> <location>/WEB-INF/405.html</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/500.jsp</location> </error-page> </web-app>
<?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>yd-tmpl-flat</display-name> <welcome-file-list> <welcome-file>home2.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- SpringMVC核心分發器 --> <!-- Web容器加載順序ServletContext /context-param/listener/filter/servlet --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- Spring會默認從WEB-INF下尋找配置文件,contextConfigLocation屬性是Spring內部固定的 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> <!-- <param-value>classpath:applicationContext.xml</param-value> --> </context-param> <!-- 防止發生java.beans.Introspector內存泄露,應將它配置在ContextLoaderListener的前面 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 應用啓動時,該監聽器被執行,它會讀取Spring相關配置文件,其默認會到WEB-INF中查找applicationContext.xml --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置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> <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> <!-- 解決亂碼問題 --> <!-- forceEncoding默認爲false,此時效果可大體理解爲request.setCharacterEncoding("UTF-8") --> <!-- forceEncoding=true後,可大體理解爲request.setCharacterEncoding("UTF-8")和response.setCharacterEncoding("UTF-8") --> <filter> <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Session超時30分鐘(零或負數表示會話永不超時)--> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- Error 頁面跳轉 --> <error-page> <error-code>405</error-code> <location>/WEB-INF/405.html</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/500.jsp</location> </error-page> </web-app>
二、spring-mvc.xml文件的配置html
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 它背後註冊了不少用於解析註解的處理器,其中就包括<context:annotation-config/>配置的註解所使用的處理器 --> <!-- 因此配置了<context:component-scan base-package="">以後,便無需再配置<context:annotation-config> --> <context:component-scan base-package="com.papio"/> <!-- 啓用SpringMVC的註解功能,它會自動註冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關實例 --> <mvc:annotation-driven/> <!-- 配置SpringMVC的視圖解析器 --> <!-- 其viewClass屬性的默認值就是org.springframework.web.servlet.view.JstlView --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 默認訪問跳轉到登陸頁面(即定義無需Controller的url<->view直接映射) --> <mvc:view-controller path="/" view-name="forward:/login.jsp"/> <!-- 因爲web.xml中設置是:由SpringMVC攔截全部請求,因而在讀取靜態資源文件的時候就會受到影響(說白了就是讀不到) --> <!-- 通過下面的配置,該標籤的做用就是:全部頁面中引用"/js/**"的資源,都會從"/resources/js/"裏面進行查找 --> <!-- 咱們能夠訪問http://IP:8080/xxx/js/my.css和http://IP:8080/xxx/resources/js/my.css對比出來 --> <mvc:resources mapping="/js/**" location="/resources/js/"/> <mvc:resources mapping="/css/**" location="/resources/css/"/> <mvc:resources mapping="/WEB-INF/**" location="/WEB-INF/"/> <!-- 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>
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 因此配置了<context:component-scan base-package="">以後,便無需再配置<context:annotation-config> --> <context:component-scan base-package="com.ydweb.data.daoimpl"/> <context:component-scan base-package="com.ydweb.data.serviceimpl"/> <!-- 啓用SpringMVC的註解功能,它會自動註冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關實例--> <mvc:annotation-driven/> <!-- 配置SpringMVC的視圖解析器 --> <!-- 其viewClass屬性的默認值就是org.springframework.web.servlet.view.JstlView --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 默認訪問跳轉到登陸頁面(即定義無需Controller的url-view直接映射) --> <mvc:view-controller path="/" view-name="forward:/login.jsp"/> <!-- 讀取靜態資源文件,通過下面的配置,該標籤的做用就是:全部頁面中引用"/js/**"的資源,都會從"/resources/js/"裏面進行查找 --> <mvc:resources mapping="/js/**" location="/resources/js/"/> <mvc:resources mapping="/css/**" location="/resources/css/"/> <mvc:resources mapping="/WEB-INF/**" location="/WEB-INF/"/> <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException --> <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> <prop key="java.lang.Throwable">WEB-INF/500</prop> </props> </property> </bean> <!-- 定義緩存管理器 --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <!-- session的失效時長,單位毫秒 --> <property name="globalSessionTimeout" value="600000"/> <!-- 刪除失效的session --> <property name="deleteInvalidSessions" value="true"/> </bean> <!-- 定義Realm --> <bean id="simpleRealm" class="com.ydweb.domain.security.SimpleRealm"></bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- Single realm app (realm configured next, below). If you have multiple realms, use the 'realms' property instead. --> <property name="realm" ref="simpleRealm" /> <!-- Uncomment this next property if you want heterogenous session access or clusterable/distributable sessions. The default value is 'http' which uses the Servlet container's HttpSession as the underlying Session implementation. <property name="sessionMode" value="native"/> --> <!-- 使用配置的緩存管理器 <property name="cacheManager" ref="cacheManager"></property> --> <!-- 會話管理 <property name="sessionManager" ref="sessionManager" />--> </bean> <!-- 配置 Bean 後置處理器: 會自動的調用和 Spring 整合後各個組件的生命週期方法. --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- ShiroFilter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/user/default/loginform" /> <property name="successUrl" value="/dashboard/user/home" /> <property name="unauthorizedUrl" value="/user/default/logout" /> <!-- The 'filters' property is usually not necessary unless performing an override, which we want to do here (make authc point to a PassthruAuthenticationFilter instead of the default FormAuthenticationFilter: --> <property name="filters"> <util:map> <entry key="authc"> <bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" /> </entry> </util:map> </property> <property name="filterChainDefinitions"> <value> /** = anon /user/default/loginform = anon /user/default/image/captcha = authc /assortment/template/home = perms[suser:view] /staffmock/template/home = perms[suser:view] /buyplan/test/home = perms[suser:view] </value> </property> </bean> </beans>
三、spring-context-shiro.xml文件配置java
<?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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" default-lazy-init="true"> <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登陸的類爲自定義的ShiroDbRealm.java --> <bean id="myRealm" class="com.papio.realm.MyRealm"/> <!-- 定義緩存管理器 --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <!-- session的失效時長,單位毫秒 --> <property name="globalSessionTimeout" value="600000"/> <!-- 刪除失效的session --> <property name="deleteInvalidSessions" value="true"/> </bean> <!-- 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="myRealm"/> <!-- 使用配置的緩存管理器 --> <property name="cacheManager" ref="cacheManager"></property> <!-- 會話管理 --> <property name="sessionManager" ref="sessionManager" /> </bean> <!-- Shiro主過濾器自己功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行 --> <!-- Web應用中,Shiro可控制的Web請求必須通過Shiro主過濾器的攔截,Shiro對基於Spring的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="/"/> <!-- 登陸成功後要跳轉的鏈接(本例中此屬性用不到,由於登陸成功後的處理邏輯在LoginController裏硬編碼爲main.jsp了) --> <!-- <property name="successUrl" value="/system/main"/> --> <!-- 用戶訪問未對其受權的資源時,所顯示的鏈接 --> <!-- 若想更明顯的測試此屬性能夠修改它的值,如unauthor.jsp,而後用[玄玉]登陸後訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp --> <property name="unauthorizedUrl" value="/"/> <!-- 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> /mydemo/login=anon /mydemo/getVerifyCodeImage=anon /main**=authc /user/info**=authc /admin/listUser**=authc,perms[admin:manage] </value> </property> </bean> <!-- 保證明現了Shiro內部lifecycle函數的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 開啓Shiro的註解(如@RequiresRoles,@RequiresPermissions),需藉助SpringAOP掃描使用Shiro註解的類,並在必要時進行安全邏輯驗證 --> <!-- 配置如下兩個bean便可實現此功能 --> <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run --> <!-- 因爲本例中並未使用Shiro註解,故註釋掉這兩個bean(我的以爲將權限經過註解的方式硬編碼在程序中,查看起來不是很方便,不必使用) --> <!-- <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> --> </beans>
四、MyRealm.java------自定義的Realm類web
package com.papio.realm; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; 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.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; /** * 自定義的指定Shiro驗證用戶登陸的類 * @see 在本例中定義了2個用戶:papio和big,papio具備admin角色和admin:manage權限,big不具備任何角色和權限 * @create * @author */ public class MyRealm extends AuthorizingRealm { /** * 爲當前登陸的Subject授予角色和權限 * @see 經測試:本例中該方法的調用時機爲需受權資源被訪問時 * @see 經測試:而且每次訪問需受權資源時都會執行該方法中的邏輯,這代表本例中默認並未啓用AuthorizationCache * @see 我的感受若使用了Spring3.1開始提供的ConcurrentMapCache支持,則可靈活決定是否啓用AuthorizationCache * @see 好比說這裏從數據庫獲取權限信息時,先去訪問Spring3.1提供的緩存,而不使用Shior提供的AuthorizationCache */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ //獲取當前登陸的用戶名,等價於(String)principals.fromRealm(this.getName()).iterator().next() String currentUsername = (String)super.getAvailablePrincipal(principals); // List<String> roleList = new ArrayList<String>(); // List<String> permissionList = new ArrayList<String>(); // //從數據庫中獲取當前登陸用戶的詳細信息 // User user = userService.getByUsername(currentUsername); // if(null != user){ // //實體類User中包含有用戶角色的實體類信息 // if(null!=user.getRoles() && user.getRoles().size()>0){ // //獲取當前登陸用戶的角色 // for(Role role : user.getRoles()){ // roleList.add(role.getName()); // //實體類Role中包含有角色權限的實體類信息 // if(null!=role.getPermissions() && role.getPermissions().size()>0){ // //獲取權限 // for(Permission pmss : role.getPermissions()){ // if(!StringUtils.isEmpty(pmss.getPermission())){ // permissionList.add(pmss.getPermission()); // } // } // } // } // } // }else{ // throw new AuthorizationException(); // } // //爲當前用戶設置角色和權限 // SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); // simpleAuthorInfo.addRoles(roleList); // simpleAuthorInfo.addStringPermissions(permissionList); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); //實際中可能會像上面註釋的那樣從數據庫取得 if(null!=currentUsername && "papio".equals(currentUsername)){ //添加一個角色,不是配置意義上的添加,而是證實該用戶擁有admin角色 simpleAuthorInfo.addRole("admin"); //添加權限 simpleAuthorInfo.addStringPermission("admin:manage"); System.out.println("已爲用戶[papio]賦予了[admin]角色和[admin:manage]權限"); return simpleAuthorInfo; }else if(null!=currentUsername && "big".equals(currentUsername)){ System.out.println("當前用戶[big]無受權"); return simpleAuthorInfo; } //若該方法什麼都不作直接返回null的話,就會致使任何用戶訪問/admin/listUser.jsp時都會自動跳轉到unauthorizedUrl指定的地址 //詳見applicationContext.xml中的<bean id="shiroFilter">的配置 return null; } /** * 驗證當前登陸的Subject * @see 經測試:本例中該方法的調用時機爲LoginController.login()方法中執行Subject.login()時 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { //獲取基於用戶名和密碼的令牌 //實際上這個authcToken是從LoginController裏面currentUser.login(token)傳過來的 //兩個token的引用都是同樣的,本例中是org.apache.shiro.authc.UsernamePasswordToken@33799a1e UsernamePasswordToken token = (UsernamePasswordToken)authcToken; System.out.println("驗證當前Subject時獲取到token爲" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); // User user = userService.getByUsername(token.getUsername()); // if(null != user){ // AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname()); // this.setSession("currentUser", user); // return authcInfo; // }else{ // return null; // } //此處無需比對,比對的邏輯Shiro會作,咱們只需返回一個和令牌相關的正確的驗證信息 //說白了就是第一個參數填登陸用戶名,第二個參數填合法的登陸密碼(能夠是從數據庫中取到的,本例中爲了演示就硬編碼了) //這樣一來,在隨後的登陸頁面上就只有這裏指定的用戶和密碼才能經過驗證 if("papio".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("papio", "papio", this.getName()); this.setSession("currentUser", "papio"); return authcInfo; }else if("big".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("big", "big", this.getName()); this.setSession("currentUser", "big"); return authcInfo; } //沒有返回登陸用戶名對應的SimpleAuthenticationInfo對象時,就會在LoginController中拋出UnknownAccountException異常 return null; } /** * 將一些數據放到ShiroSession中,以便於其它地方使用 * @see 好比Controller,使用時直接用HttpSession.getAttribute(key)就能夠取到 */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); System.out.println("Session默認超時時間爲[" + session.getTimeout() + "]毫秒"); if(null != session){ session.setAttribute(key, value); } } } }
五、LoginController.java------處理用戶登陸spring
package com.papio.controller; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.util.WebUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * 本例中用到的jar文件以下 * @see aopalliance.jar * @see commons-lang3-3.1.jar * @see commons-logging-1.1.2.jar * @see log4j-1.2.17.jar * @see shiro-all-1.2.2.jar * @see slf4j-api-1.7.5.jar * @see slf4j-log4j12-1.7.5.jar * @see spring-aop-3.2.4.RELEASE.jar * @see spring-beans-3.2.4.RELEASE.jar * @see spring-context-3.2.4.RELEASE.jar * @see spring-core-3.2.4.RELEASE.jar * @see spring-expression-3.2.4.RELEASE.jar * @see spring-jdbc-3.2.4.RELEASE.jar * @see spring-oxm-3.2.4.RELEASE.jar * @see spring-tx-3.2.4.RELEASE.jar * @see spring-web-3.2.4.RELEASE.jar * @see spring-webmvc-3.2.4.RELEASE.jar * @create Sep 30, 2013 11:10:06 PM */ @Controller @RequestMapping("mydemo") public class LoginController { /** * 用戶登陸 */ @RequestMapping(value="/login", method=RequestMethod.POST) public String login(HttpServletRequest request){ String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/"; String username = request.getParameter("username"); String password = request.getParameter("password"); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); System.out.println("爲了驗證登陸用戶而封裝的token爲" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); //獲取當前的Subject Subject currentUser = SecurityUtils.getSubject(); try { //在調用了login方法後,SecurityManager會收到AuthenticationToken,並將其發送給已配置的Realm執行必須的認證檢查 //每一個Realm都能在必要時對提交的AuthenticationTokens做出反應 //因此這一步在調用login(token)方法時,它會走到MyRealm.doGetAuthenticationInfo()方法中,具體驗證方式詳見此方法 System.out.println("對用戶[" + username + "]進行登陸驗證..驗證開始"); currentUser.login(token); System.out.println("對用戶[" + username + "]進行登陸驗證..驗證經過"); resultPageURL = "main"; }catch(UnknownAccountException uae){ System.out.println("對用戶[" + username + "]進行登陸驗證..驗證未經過,未知帳戶"); request.setAttribute("message_login", "未知帳戶"); }catch(IncorrectCredentialsException ice){ System.out.println("對用戶[" + username + "]進行登陸驗證..驗證未經過,錯誤的憑證"); request.setAttribute("message_login", "密碼不正確"); }catch(LockedAccountException lae){ System.out.println("對用戶[" + username + "]進行登陸驗證..驗證未經過,帳戶已鎖定"); request.setAttribute("message_login", "帳戶已鎖定"); }catch(ExcessiveAttemptsException eae){ System.out.println("對用戶[" + username + "]進行登陸驗證..驗證未經過,錯誤次數過多"); request.setAttribute("message_login", "用戶名或密碼錯誤次數過多"); }catch(AuthenticationException ae){ //經過處理Shiro的運行時AuthenticationException就能夠控制用戶登陸失敗或密碼錯誤時的情景 System.out.println("對用戶[" + username + "]進行登陸驗證..驗證未經過,堆棧軌跡以下"); ae.printStackTrace(); request.setAttribute("message_login", "用戶名或密碼不正確"); } //驗證是否登陸成功 if(currentUser.isAuthenticated()){ System.out.println("用戶[" + username + "]登陸認證經過(這裏能夠進行一些認證經過後的一些系統參數初始化操做)"); }else{ token.clear(); } return resultPageURL; } /** * 用戶登出 */ @RequestMapping("/logout") public String logout(HttpServletRequest request){ SecurityUtils.getSubject().logout(); return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/"; } }
六、UserController.java------處理普通用戶訪問數據庫
package com.papio.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("mydemo") public class UserController { @RequestMapping(value="/getUserInfo") public String getUserInfo(HttpServletRequest request){ String currentUser = (String)request.getSession().getAttribute("currentUser"); System.out.println("當前登陸的用戶爲[" + currentUser + "]"); request.setAttribute("currUser", currentUser); return "/user/info"; } }