SpringMVC整合Shiro

這裏用的是SpringMVC-3.2.4和Shiro-1.2.2,示例代碼如下


首先是web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     <!-- Web容器加載順序ServletContext--context-param--listener--filter--servlet -->  
  8.   
  9.     <!-- 指定Spring的配置文件 -->  
  10.     <!-- 否則Spring會默認從WEB-INF下尋找配置文件,contextConfigLocation屬性是Spring內部固定的 -->  
  11.     <!-- 通過ContextLoaderListener的父類ContextLoader的第120行發現CONFIG_LOCATION_PARAM固定爲contextConfigLocation -->  
  12.     <context-param>  
  13.         <param-name>contextConfigLocation</param-name>  
  14.         <param-value>classpath:applicationContext.xml</param-value>  
  15.     </context-param>  
  16.   
  17.     <!-- 防止發生java.beans.Introspector內存泄露,應將它配置在ContextLoaderListener的前面 -->  
  18.     <!-- 詳細描述見http://blog.csdn.net/jadyer/article/details/11991457 -->  
  19.     <listener>  
  20.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  21.     </listener>  
  22.       
  23.     <!-- 實例化Spring容器 -->  
  24.     <!-- 應用啓動時,該監聽器被執行,它會讀取Spring相關配置文件,其默認會到WEB-INF中查找applicationContext.xml -->  
  25.     <!-- http://starscream.iteye.com/blog/1107036 -->  
  26.     <!-- http://www.davenkin.me/post/2012-10-18/40039948363 -->  
  27.     <!-- WebApplicationContextUtils.getWebApplicationContext() -->  
  28.     <listener>  
  29.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  30.     </listener>  
  31.   
  32.     <!-- 解決亂碼問題 -->  
  33.     <!-- forceEncoding默認爲false,此時效果可大致理解爲request.setCharacterEncoding("UTF-8") -->  
  34.     <!-- forceEncoding=true後,可大致理解爲request.setCharacterEncoding("UTF-8")和response.setCharacterEncoding("UTF-8") -->  
  35.     <filter>  
  36.         <filter-name>SpringEncodingFilter</filter-name>  
  37.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  38.         <init-param>  
  39.             <param-name>encoding</param-name>  
  40.             <param-value>UTF-8</param-value>  
  41.         </init-param>  
  42.         <init-param>  
  43.             <param-name>forceEncoding</param-name>  
  44.             <param-value>true</param-value>  
  45.         </init-param>  
  46.     </filter>  
  47.     <filter-mapping>  
  48.         <filter-name>SpringEncodingFilter</filter-name>  
  49.         <url-pattern>/*</url-pattern>  
  50.     </filter-mapping>  
  51.       
  52.     <!-- 配置Shiro過濾器,先讓Shiro過濾系統接收到的請求 -->  
  53.     <!-- 這裏filter-name必須對應applicationContext.xml中定義的<bean id="shiroFilter"/> -->  
  54.     <!-- 使用[/*]匹配所有請求,保證所有的可控請求都經過Shiro的過濾 -->  
  55.     <!-- 通常會將此filter-mapping放置到最前面(即其他filter-mapping前面),以保證它是過濾器鏈中第一個起作用的 -->  
  56.     <filter>  
  57.         <filter-name>shiroFilter</filter-name>  
  58.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  59.         <init-param>  
  60.             <!-- 該值缺省爲false,表示生命週期由SpringApplicationContext管理,設置爲true則表示由ServletContainer管理 -->  
  61.             <param-name>targetFilterLifecycle</param-name>  
  62.             <param-value>true</param-value>  
  63.         </init-param>  
  64.     </filter>  
  65.     <filter-mapping>  
  66.         <filter-name>shiroFilter</filter-name>  
  67.         <url-pattern>/*</url-pattern>  
  68.     </filter-mapping>  
  69.   
  70.     <!-- SpringMVC核心分發器 -->  
  71.     <servlet>  
  72.         <servlet-name>SpringMVC</servlet-name>  
  73.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  74.         <init-param>  
  75.             <param-name>contextConfigLocation</param-name>  
  76.             <param-value>classpath:applicationContext.xml</param-value>  
  77.         </init-param>  
  78.     </servlet>  
  79.     <servlet-mapping>  
  80.         <servlet-name>SpringMVC</servlet-name>  
  81.         <url-pattern>/</url-pattern>  
  82.     </servlet-mapping>  
  83.   
  84.     <!-- Session超時30分鐘(零或負數表示會話永不超時) -->  
  85.     <!--   
  86.     <session-config>  
  87.         <session-timeout>30</session-timeout>  
  88.     </session-config>  
  89.      -->  
  90.   
  91.     <!-- 默認歡迎頁 -->  
  92.     <!-- Servlet2.5中可直接在此處執行Servlet應用,如<welcome-file>servlet/InitSystemParamServlet</welcome-file> -->  
  93.     <!-- 這裏使用了SpringMVC提供的<mvc:view-controller>標籤,實現了首頁隱藏的目的,詳見applicationContext.xml -->  
  94.     <!--   
  95.     <welcome-file-list>  
  96.         <welcome-file>login.jsp</welcome-file>  
  97.     </welcome-file-list>  
  98.      -->  
  99.       
  100.     <error-page>  
  101.         <error-code>405</error-code>  
  102.         <location>/WEB-INF/405.html</location>  
  103.     </error-page>  
  104.     <error-page>  
  105.         <error-code>404</error-code>  
  106.         <location>/WEB-INF/404.jsp</location>  
  107.     </error-page>  
  108.     <error-page>  
  109.         <error-code>500</error-code>  
  110.         <location>/WEB-INF/500.jsp</location>  
  111.     </error-page>  
  112.     <error-page>  
  113.         <exception-type>java.lang.Throwable</exception-type>  
  114.         <location>/WEB-INF/500.jsp</location>  
  115.     </error-page>  
  116. </web-app>  
下面是用於顯示Request method 'GET' not supported的//WebRoot//WEB-INF//405.html

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  2. <html>  
  3.     <head>  
  4.         <title>405.html</title>  
  5.         <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  6.     </head>  
  7.     <body>  
  8.         <font color="blue">  
  9.             Request method 'GET' not supported  
  10.             <br/><br/>  
  11.             The specified HTTP method is not allowed for the requested resource.  
  12.         </font>  
  13.     </body>  
  14. </html>  
下面是允許匿名用戶訪問的//WebRoot//login.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2.   
  3. <script type="text/javascript">  
  4. <!--  
  5. function reloadVerifyCode(){  
  6.     document.getElementById('verifyCodeImage').setAttribute('src', '${pageContext.request.contextPath}/mydemo/getVerifyCodeImage');  
  7. }  
  8. //-->  
  9. </script>  
  10.   
  11. <div style="color:red; font-size:22px;">${message_login}</div>  
  12.   
  13. <form action="<%=request.getContextPath()%>/mydemo/login" method="POST">  
  14.     姓名:<input type="text" name="username"/><br/>  
  15.     密碼:<input type="text" name="password"/><br/>  
  16.     驗證:<input type="text" name="verifyCode"/>  
  17.          &nbsp;&nbsp;  
  18.          <img id="verifyCodeImage" onclick="reloadVerifyCode()" src="<%=request.getContextPath()%>/mydemo/getVerifyCodeImage"/><br/>  
  19.     <input type="submit" value="確認"/>  
  20. </form>  
下面是用戶登錄後顯示的//WebRoot//main.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 普通用戶可訪問<a href="<%=request.getContextPath()%>/mydemo/getUserInfo" target="_blank">用戶信息頁面</a>  
  3. <br/>  
  4. <br/>  
  5. 管理員可訪問<a href="<%=request.getContextPath()%>/admin/listUser.jsp" target="_blank">用戶列表頁面</a>  
  6. <br/>  
  7. <br/>  
  8. <a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>  
下面是隻有管理員才允許訪問的//WebRoot//admin//listUser.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. This is listUser.jsp  
  3. <br/>  
  4. <br/>  
  5. <a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>  
下面是普通的登錄用戶所允許訪問的//WebRoot//user//info.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 當前登錄的用戶爲${currUser}  
  3. <br/>  
  4. <br/>  
  5. <a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>  
下面是//src//log4j.properties

  1. #use Root for GobalConfig  
  2. log4j.rootLogger=DEBUG,CONSOLE  
  3.   
  4. log4j.logger.java.sql=DEBUG  
  5. log4j.logger.org.apache.shiro=DEBUG  
  6. log4j.logger.org.apache.commons=DEBUG  
  7. log4j.logger.org.springframework=DEBUG  
  8.   
  9. #use ConsoleAppender for ConsoleOut  
  10. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  
  11. log4j.appender.CONSOLE.Threshold=DEBUG  
  12. log4j.appender.CONSOLE.Target=System.out  
  13. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  
  14. log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyyMMdd HH:mm:ss}][%t][%C{1}.%M]%m%n  
下面是//src//applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.                         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  8.                         http://www.springframework.org/schema/mvc  
  9.                         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  10.                         http://www.springframework.org/schema/context  
  11.                         http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  12.     <!-- 它背後註冊了很多用於解析註解的處理器,其中就包括<context:annotation-config/>配置的註解所使用的處理器 -->  
  13.     <!-- 所以配置了<context:component-scan base-package="">之後,便無需再配置<context:annotation-config> -->  
  14.     <context:component-scan base-package="com.jadyer"/>  
  15.       
  16.     <!-- 啓用SpringMVC的註解功能,它會自動註冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關實例 -->  
  17.     <mvc:annotation-driven/>  
  18.   
  19.     <!-- 配置SpringMVC的視圖解析器 -->  
  20.     <!-- 其viewClass屬性的默認值就是org.springframework.web.servlet.view.JstlView -->  
  21.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  22.         <property name="prefix" value="/"/>  
  23.         <property name="suffix" value=".jsp"/>  
  24.     </bean>  
  25.   
  26.     <!-- 默認訪問跳轉到登錄頁面(即定義無需Controller的url<->view直接映射) -->  
  27.     <mvc:view-controller path="/" view-name="forward:/login.jsp"/>  
  28.   
  29.     <!-- 由於web.xml中設置是:由SpringMVC攔截所有請求,於是在讀取靜態資源文件的時候就會受到影響(說白了就是讀不到) -->  
  30.     <!-- 經過下面的配置,該標籤的作用就是:所有頁面中引用"/js/**"的資源,都會從"/resources/js/"裏面進行查找 -->  
  31.     <!-- 我們可以訪問http://IP:8080/xxx/js/my.css和http://IP:8080/xxx/resources/js/my.css對比出來 -->  
  32.     <mvc:resources mapping="/js/**" location="/resources/js/"/>  
  33.     <mvc:resources mapping="/css/**" location="/resources/css/"/>  
  34.     <mvc:resources mapping="/WEB-INF/**" location="/WEB-INF/"/>  
  35.   
  36.     <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
  37.     <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進入到Controller方法中 -->  
  38.     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  39.         <property name="exceptionMappings">  
  40.             <props>  
  41.                 <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/error_fileupload.jsp頁面 -->  
  42.                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">WEB-INF/error_fileupload</prop>  
  43.                 <!-- 處理其它異常(包括Controller拋出的) -->  
  44.                 <prop key="java.lang.Throwable">WEB-INF/500</prop>  
  45.             </props>  
  46.         </property>  
  47.     </bean>  
  48.   
  49.     <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類爲自定義的ShiroDbRealm.java -->  
  50.     <bean id="myRealm" class="com.jadyer.realm.MyRealm"/>  
  51.   
  52.     <!-- Shiro默認會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session -->  
  53.     <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 -->  
  54.     <!-- 這裏主要是設置自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 -->  
  55.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  56.         <property name="realm" ref="myRealm"/>  
  57.     </bean>  
  58.   
  59.     <!-- Shiro主過濾器本身功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行 -->  
  60.     <!-- Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支持 -->  
  61.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  62.         <!-- Shiro的核心安全接口,這個屬性是必須的 -->  
  63.         <property name="securityManager" ref="securityManager"/>  
  64.         <!-- 要求登錄時的鏈接(可根據項目的URL進行替換),非必須的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->  
  65.         <property name="loginUrl" value="/"/>  
  66.         <!-- 登錄成功後要跳轉的連接(本例中此屬性用不到,因爲登錄成功後的處理邏輯在LoginController裏硬編碼爲main.jsp了) -->  
  67.         <!-- <property name="successUrl" value="/system/main"/> -->  
  68.         <!-- 用戶訪問未對其授權的資源時,所顯示的連接 -->  
  69.         <!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然後用[玄玉]登錄後訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp -->  
  70.         <property name="unauthorizedUrl" value="/"/>  
  71.         <!-- Shiro連接約束配置,即過濾鏈的定義 -->  
  72.         <!-- 此處可配合我的這篇文章來理解各個過濾連的作用http://blog.csdn.net/jadyer/article/details/12172839 -->  
  73.         <!-- 下面value值的第一個'/'代表的路徑是相對於HttpServletRequest.getContextPath()的值來的 -->  
  74.         <!-- anon:它對應的過濾器裏面是空的,什麼都沒做,這裏.do和.jsp後面的*表示參數,比方說login.jsp?main這種 -->  
  75.         <!-- authc:該過濾器下的頁面必須驗證後才能訪問,它是Shiro內置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->  
  76.         <property name="filterChainDefinitions">  
  77.             <value>  
  78.                 /mydemo/login=anon  
  79.                 /mydemo/getVerifyCodeImage=anon  
  80.                 /main**=authc  
  81.                 /user/info**=authc  
  82.                 /admin/listUser**=authc,perms[admin:manage]  
  83.             </value>  
  84.         </property>  
  85.     </bean>  
  86.   
  87.     <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->  
  88.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
  89.   
  90.     <!-- 開啓Shiro的註解(如@RequiresRoles,@RequiresPermissions),需藉助SpringAOP掃描使用Shiro註解的類,並在必要時進行安全邏輯驗證 -->  
  91.     <!-- 配置以下兩個bean即可實現此功能 -->  
  92.     <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->  
  93.     <!-- 由於本例中並未使用Shiro註解,故註釋掉這兩個bean(個人覺得將權限通過註解的方式硬編碼在程序中,查看起來不是很方便,沒必要使用) -->  
  94.     <!--   
  95.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>  
  96.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  97.         <property name="securityManager" ref="securityManager"/>  
  98.     </bean>  
  99.      -->  
  100. </beans>  
下面是自定義的Realm類----MyRealm.java

  1. package com.jadyer.realm;  
  2.   
  3. import org.apache.commons.lang3.builder.ReflectionToStringBuilder;  
  4. import org.apache.commons.lang3.builder.ToStringStyle;  
  5. import org.apache.shiro.SecurityUtils;  
  6. import org.apache.shiro.authc.AuthenticationException;  
  7. import org.apache.shiro.authc.AuthenticationInfo;  
  8. import org.apache.shiro.authc.AuthenticationToken;  
  9. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  10. import org.apache.shiro.authc.UsernamePasswordToken;  
  11. import org.apache.shiro.authz.AuthorizationInfo;  
  12. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  13. import org.apache.shiro.realm.AuthorizingRealm;  
  14. import org.apache.shiro.session.Session;  
  15. import org.apache.shiro.subject.PrincipalCollection;  
  16. import org.apache.shiro.subject.Subject;  
  17.   
  18. /** 
  19.  * 自定義的指定Shiro驗證用戶登錄的類 
  20.  * @see 在本例中定義了2個用戶:jadyer和玄玉,jadyer具有admin角色和admin:manage權限,玄玉不具有任何角色和權限 
  21.  * @create Sep 29, 2013 3:15:31 PM 
  22.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  23.  */  
  24. public class MyRealm extends AuthorizingRealm {  
  25.     /** 
  26.      * 爲當前登錄的Subject授予角色和權限 
  27.      * @see 經測試:本例中該方法的調用時機爲需授權資源被訪問時 
  28.      * @see 經測試:並且每次訪問需授權資源時都會執行該方法中的邏輯,這表明本例中默認並未啓用AuthorizationCache 
  29.      * @see 個人感覺若使用了Spring3.1開始提供的ConcurrentMapCache支持,則可靈活決定是否啓用AuthorizationCache 
  30.      * @see 比如說這裏從數據庫獲取權限信息時,先去訪問Spring3.1提供的緩存,而不使用Shior提供的AuthorizationCache 
  31.      */  
  32.     @Override  
  33.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
  34.         //獲取當前登錄的用戶名,等價於(String)principals.fromRealm(this.getName()).iterator().next()  
  35.         String currentUsername = (String)super.getAvailablePrincipal(principals);  
  36. //      List<String> roleList = new ArrayList<String>();  
  37. //      List<String> permissionList = new ArrayList<String>();  
  38. //      //從數據庫中獲取當前登錄用戶的詳細信息  
  39. //      User user = userService.getByUsername(currentUsername);  
  40. //      if(null != user){  
  41. //          //實體類User中包含有用戶角色的實體類信息  
  42. //          if(null!=user.getRoles() && user.getRoles().size()>0){  
  43. //              //獲取當前登錄用戶的角色  
  44. //              for(Role role : user.getRoles()){  
  45. //                  roleList.add(role.getName());  
  46. //                  //實體類Role中包含有角色權限的實體類信息  
  47. //                  if(null!=role.getPermissions() && role.getPermissions().size()>0){  
  48. //                      //獲取權限  
  49. //                      for(Permission pmss : role.getPermissions()){  
  50. //                          if(!StringUtils.isEmpty(pmss.getPermission())){  
  51. //                              permissionList.add(pmss.getPermission());  
  52. //                          }  
  53. //                      }  
  54. //                  }  
  55. //              }  
  56. //          }  
  57. //      }else{  
  58. //          throw new AuthorizationException();  
  59. //      }  
  60. //      //爲當前用戶設置角色和權限  
  61. //      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
  62. //      simpleAuthorInfo.addRoles(roleList);  
  63. //      simpleAuthorInfo.addStringPermissions(permissionList);  
  64.         SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
  65.         //實際中可能會像上面註釋的那樣從數據庫取得  
  66.         if(null!=currentUsername && "jadyer".equals(currentUsername)){  
  67.             //添加一個角色,不是配置意義上的添加,而是證明該用戶擁有admin角色    
  68.             simpleAuthorInfo.addRole("admin");  
  69.             //添加權限  
  70.             simpleAuthorInfo.addStringPermission("admin:manage");  
  71.             System.out.println("已爲用戶[jadyer]賦予了[admin]角色和[admin:manage]權限");  
  72.             return simpleAuthorInfo;  
  73.         }else if(null!=currentUsername && "玄玉".equals(currentUsername)){  
  74.             System.out.println("當前用戶[玄玉]無授權");  
  75.             return simpleAuthorInfo;  
  76.         }  
  77.         //若該方法什麼都不做直接返回null的話,就會導致任何用戶訪問/admin/listUser.jsp時都會自動跳轉到unauthorizedUrl指定的地址  
  78.         //詳見applicationContext.xml中的<bean id="shiroFilter">的配置  
  79.         return null;  
  80.     }  
  81.   
  82.       
  83.     /** 
  84.      * 驗證當前登錄的Subject 
  85.      * @see 經測試:本例中該方法的調用時機爲LoginController.login()方法中執行Subject.login()時 
  86.      */  
  87.     @Override  
  88.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
  89.         //獲取基於用戶名和密碼的令牌  
  90.         //實際上這個authcToken是從LoginController裏面currentUser.login(token)傳過來的  
  91.         //兩個token的引用都是一樣的,本例中是org.apache.shiro.authc.UsernamePasswordToken@33799a1e  
  92.         UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
  93.         System.out.println("驗證當前Subject時獲取到token爲" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
  94. //      User user = userService.getByUsername(token.getUsername());  
  95. //      if(null != user){  
  96. //          AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname());  
  97. //          this.setSession("currentUser", user);  
  98. //          return authcInfo;  
  99. //      }else{  
  100. //          return null;  
  101. //      }  
  102.         //此處無需比對,比對的邏輯Shiro會做,我們只需返回一個和令牌相關的正確的驗證信息  
  103.         //說白了就是第一個參數填登錄用戶名,第二個參數填合法的登錄密碼(可以是從數據庫中取到的,本例中爲了演示就硬編碼了)  
  104.         //這樣一來,在隨後的登錄頁面上就只有這裏指定的用戶和密碼才能通過驗證  
  105.         if("jadyer".equals(token.getUsername())){  
  106.             AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("jadyer""jadyer"this.getName());  
  107.             this.setSession("currentUser""jadyer");  
  108.             return authcInfo;  
  109.         }else if("玄玉".equals(token.getUsername())){  
  110.             AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("玄玉""xuanyu"this.getName());  
  111.             this.setSession("currentUser""玄玉");  
  112.             return authcInfo;  
  113.         }  
  114.         //沒有返回登錄用戶名對應的SimpleAuthenticationInfo對象時,就會在LoginController中拋出UnknownAccountException異常  
  115.         return null;  
  116.     }  
  117.       
  118.       
  119.     /** 
  120.      * 將一些數據放到ShiroSession中,以便於其它地方使用 
  121.      * @see 比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到 
  122.      */  
  123.     private void setSession(Object key, Object value){  
  124.         Subject currentUser = SecurityUtils.getSubject();  
  125.         if(null != currentUser){  
  126.             Session session = currentUser.getSession();  
  127.             System.out.println("Session默認超時時間爲[" + session.getTimeout() + "]毫秒");  
  128.             if(null != session){  
  129.                 session.setAttribute(key, value);  
  130.             }  
  131.         }  
  132.     }  
  133. }  
下面是處理用戶登錄的LoginController.java

  1. package com.jadyer.controller;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.image.BufferedImage;  
  5. import java.io.IOException;  
  6.   
  7. import javax.imageio.ImageIO;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.apache.commons.lang3.StringUtils;  
  12. import org.apache.commons.lang3.builder.ReflectionToStringBuilder;  
  13. import org.apache.commons.lang3.builder.ToStringStyle;  
  14. import org.apache.shiro.SecurityUtils;  
  15. import org.apache.shiro.authc.AuthenticationException;  
  16. import org.apache.shiro.authc.ExcessiveAttemptsException;  
  17. import org.apache.shiro.authc.IncorrectCredentialsException;  
  18. import org.apache.shiro.authc.LockedAccountException;  
  19. import org.apache.shiro.authc.UnknownAccountException;  
  20. import org.apache.shiro.authc.UsernamePasswordToken;  
  21. import org.apache.shiro.subject.Subject;  
  22. import org.apache.shiro.web.util.WebUtils;  
  23. import org.springframework.stereotype.Controller;  
  24. import org.springframework.web.bind.annotation.RequestMapping;  
  25. import org.springframework.web.bind.annotation.RequestMethod;  
  26. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  27.   
  28. import com.jadyer.util.VerifyCodeUtil;  
  29.   
  30. /** 
  31.  * 本例中用到的jar文件如下 
  32.  * @see aopalliance.jar 
  33.  * @see commons-lang3-3.1.jar 
  34.  * @see commons-logging-1.1.2.jar 
  35.  * @see log4j-1.2.17.jar 
  36.  * @see shiro-all-1.2.2.jar 
  37.  * @see slf4j-api-1.7.5.jar 
  38.  * @see slf4j-log4j12-1.7.5.jar 
  39.  * @see spring-aop-3.2.4.RELEASE.jar 
  40.  * @see spring-beans-3.2.4.RELEASE.jar 
  41.  * @see spring-context-3.2.4.RELEASE.jar 
  42.  * @see spring-core-3.2.4.RELEASE.jar 
  43.  * @see spring-expression-3.2.4.RELEASE.jar 
  44.  * @see spring-jdbc-3.2.4.RELEASE.jar 
  45.  * @see spring-oxm-3.2.4.RELEASE.jar 
  46.  * @see spring-tx-3.2.4.RELEASE.jar 
  47.  * @see spring-web-3.2.4.RELEASE.jar 
  48.  * @see spring-webmvc-3.2.4.RELEASE.jar 
  49.  * @create Sep 30, 2013 11:10:06 PM 
  50.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  51.  */  
  52. @Controller  
  53. @RequestMapping("mydemo")  
  54. public class LoginController {  
  55.     /** 
  56.      * 獲取驗證碼圖片和文本(驗證碼文本會保存在HttpSession中) 
  57.      */  
  58.     @RequestMapping("/getVerifyCodeImage")  
  59.     public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {  
  60.         //設置頁面不緩存  
  61.         response.setHeader("Pragma""no-cache");  
  62.         response.setHeader("Cache-Control""no-cache");  
  63.         response.setDateHeader("Expires"0);  
  64.         String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4null);  
  65.         //將驗證碼放到HttpSession裏面  
  66.         request.getSession().setAttribute("verifyCode", verifyCode);  
  67.         System.out.println("本次生成的驗證碼爲[" + verifyCode + "],已存放到HttpSession中");  
  68.         //設置輸出的內容的類型爲JPEG圖像  
  69.         response.setContentType("image/jpeg");  
  70.         BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90303true, Color.WHITE, Color.BLACK, null);  
  71.         //寫給瀏覽器  
  72.         ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());  
  73.     }  
  74.       
  75.       
  76.     /** 
  77.      * 用戶登錄 
  78.      */  
  79.     @RequestMapping(value="/login", method=RequestMethod.POST)  
  80.     public String login(HttpServletRequest request){  
  81.         String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";  
  82.         String username = request.getParameter("username");  
  83.         String password = request.getParameter("password");  
  84.         //獲取HttpSession中的驗證碼  
  85.         String verifyCode = (String)request.getSession().getAttribute("verifyCode");  
  86.         //獲取用戶請求表單中輸入的驗證碼  
  87.         String submitCode = WebUtils.getCleanParam(request, "verifyCode");  
  88.         System.out.println("用戶[" + username + "]登錄時輸入的驗證碼爲[" + submitCode + "],HttpSession中的驗證碼爲[" + verifyCode + "]");  
  89.         if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){  
  90.             request.setAttribute("message_login""驗證碼不正確");  
  91.             return resultPageURL;  
  92.         }  
  93.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  94.         token.setRememberMe(true);  
  95.         System.out.println("爲了驗證登錄用戶而封裝的token爲" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
  96.         //獲取當前的Subject  
  97.         Subject currentUser = SecurityUtils.getSubject();  
  98.         try {  
  99.             //在調用了login方法後,SecurityManager會收到AuthenticationToken,並將其發送給已配置的Realm執行必須的認證檢查  
  100.             //每個Realm都能在必要時對提交的AuthenticationTokens作出反應  
  101.             //所以這一步在調用login(token)方法時,它會走到MyRealm.doGetAuthenticationInfo()方法中,具體驗證方式詳見此方法  
  102.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證開始");  
  103.             currentUser.login(token);  
  104.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證通過");  
  105.             resultPageURL = "main";  
  106.         }catch(UnknownAccountException uae){  
  107.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證未通過,未知賬戶");  
  108.             request.setAttribute("message_login""未知賬戶");  
  109.         }catch(IncorrectCredentialsException ice){  
  110.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證未通過,錯誤的憑證");  
  111.             request.setAttribute("message_login""密碼不正確");  
  112.         }catch(LockedAccountException lae){  
  113.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證未通過,賬戶已鎖定");  
  114.             request.setAttribute("message_login""賬戶已鎖定");  
  115.         }catch(ExcessiveAttemptsException eae){  
  116.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證未通過,錯誤次數過多");  
  117.             request.setAttribute("message_login""用戶名或密碼錯誤次數過多");  
  118.         }catch(AuthenticationException ae){  
  119.             //通過處理Shiro的運行時AuthenticationException就可以控制用戶登錄失敗或密碼錯誤時的情景  
  120.             System.out.println("對用戶[" + username + "]進行登錄驗證..驗證未通過,堆棧軌跡如下");  
  121.             ae.printStackTrace();  
  122.             request.setAttribute("message_login""用戶名或密碼不正確");  
  123.         }  
  124.         //驗證是否登錄成功  
  125.         if(currentUser.isAuthenticated()){  
  126.             System.out.println("用戶[" + username + "]登錄認證通過(這裏可以進行一些認證通過後的一些系統參數初始化操作)");  
  127.         }else{  
  128.             token.clear();  
  129.         }  
  130.         return resultPageURL;  
  131.     }  
  132.       
  133.       
  134.     /** 
  135.      * 用戶登出 
  136.      */  
  137.     @RequestMapping("/logout")  
  138.     public String logout(HttpServletRequest request){  
  139.          SecurityUtils.getSubject().logout();  
  140.          return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/";  
  141.     }  
  142. }  
下面是處理普通用戶訪問的UserController.java

  1. package com.jadyer.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7.   
  8. @Controller  
  9. @RequestMapping("mydemo")  
  10. public class UserController {  
  11.     @RequestMapping(value="/getUserInfo")  
  12.     public String getUserInfo(HttpServletRequest request){  
  13.         String currentUser = (String)request.getSession().getAttribute("currentUser");  
  14.         System.out.println("當前登錄的用戶爲[" + currentUser + "]");  
  15.         request.setAttribute("currUser", currentUser);  
  16.         return "/user/info";  
  17.     }  
  18. }  
最後是用於生成登錄驗證碼的VerifyCodeUtil.java

  1. package com.jadyer.util;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.image.BufferedImage;  
  7. import java.util.Random;  
  8.   
  9. /** 
  10.  * 驗證碼生成器 
  11.  * @see -------------------------------------------------------------------------------------------------------------- 
  12.  * @see 可生成數字、大寫、小寫字母及三者混合類型的驗證碼 
  13.  * @see 支持自定義驗證碼字符數量,支持自定義驗證碼圖片的大小,支持自定義需排除的特殊字符,支持自定義干擾線的數量,支持自定義驗證碼圖文顏色 
  14.  * @see -------------------------------------------------------------------------------------------------------------- 
  15.  * @see 另外,給Shiro加入驗證碼有多種方式,也可以通過繼承修改FormAuthenticationFilter類,通過Shiro去驗證驗證碼 
  16.  * @see 而這裏既然使用了SpringMVC,也爲了簡化操作,就使用此工具生成驗證碼,並在Controller中處理驗證碼的校驗 
  17.  * @see -------------------------------------------------------------------------------------------------------------- 
  18.  * @create Sep 29, 2013 4:23:13 PM 
  19.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  20.  */  
  21. public class VerifyCodeUtil {  
  22.     /** 
  23.      * 驗證碼類型爲僅數字,即0~9 
  24.      */  
  25.     public static final int TYPE_NUM_ONLY = 0;  
  26.   
  27.     /** 
  28.      * 驗證碼類型爲僅字母,即大小寫字母混合 
  29.      */  
  30.     public static final int TYPE_LETTER_ONLY = 1;  
  31.   
  32.     /** 
  33.      * 驗證碼類型爲數字和大小寫字母混合 
  34.      */  
  35.     public static final int TYPE_ALL_MIXED = 2;  
  36.   
  37.     /** 
  38.      * 驗證碼類型爲數字和大寫字母混合 
  39.      */  
  40.     public static final int TYPE_NUM_UPPER = 3;  
  41.   
  42.     /** 
  43.      * 驗證碼類型爲數字和小寫字母混合 
  44.      */  
  45.     public static final int TYPE_NUM_LOWER = 4;  
  46.   
  47.     /** 
  48.      * 驗證碼類型爲僅大寫字母 
  49.      */  
  50.     public static final int TYPE_UPPER_ONLY = 5;  
  51.   
  52.     /** 
  53.      * 驗證碼類型爲僅小寫字母 
  54.      */  
  55.     public static final int TYPE_LOWER_ONLY = 6;  
  56.   
  57.     private VerifyCodeUtil(){}  
  58.       
  59.     /** 
  60.      * 生成隨機顏色 
  61.      */  
  62.     private static Color generateRandomColor() {  
  63.         Random random = new Random();  
  64.         return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));  
  65.     }  
  66.       
  67.       
  68.     /** 
  69.      * 生成圖片驗證碼 
  70.      * @param type           驗證碼類型,參見本類的靜態屬性 
  71.      * @param length         驗證碼字符長度,要求大於0的整數 
  72.      * @param excludeString  需排除的特殊字符 
  73.      * @param width          圖片寬度(注意此寬度若過小,容易造成驗證碼文本顯示不全,如4個字符的文本可使用85到90的寬度) 
  74.      * @param height         圖片高度 
  75.      * @param interLine      圖片中干擾線的條數 
  76.      * @param randomLocation 每個字符的高低位置是否隨機 
  77.      * @param backColor      圖片顏色,若爲null則表示採用隨機顏色 
  78.      * @param foreColor      字體顏色,若爲null則表示採用隨機顏色 
  79.      * @param lineColor      干擾線顏色,若爲null則表示採用隨機顏色 
  80.      * @return 圖片緩存對象 
  81.      */  
  82.     public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){  
  83.         String textCode = generateTextCode(type, length, excludeString);  
  84.         return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor);  
  85.     }  
  86.       
  87.   
  88.     /** 
  89.      * 生成驗證碼字符串 
  90.      * @param type          驗證碼類型,參見本類的靜態屬性 
  91.      * @param length        驗證碼長度,要求大於0的整數 
  92.      * @param excludeString 需排除的特殊字符(無需排除則爲null) 
  93.      * @return 驗證碼字符串 
  94.      */  
  95.     public static String generateTextCode(int type, int length, String excludeString){  
  96.         if(length <= 0){  
  97.             return "";  
  98.         }  
  99.         StringBuffer verifyCode = new StringBuffer();  
  100.         int i = 0;  
  101.         Random random = new Random();  
  102.         switch(type){  
  103.             case TYPE_NUM_ONLY:  
  104.                 while(i < length){  
  105.                     int t = random.nextInt(10);  
  106.                     //排除特殊字符  
  107.                     if(null==excludeString || excludeString.indexOf(t+"")<0) {  
  108.                         verifyCode.append(t);  
  109.                         i++;  
  110.                     }  
  111.                 }  
  112.             break;  
  113.             case TYPE_LETTER_ONLY:  
  114.                 while(i < length){  
  115.                     int t = random.nextInt(123);  
  116.                     if((t>=97 || (t>=65&&t<=90)) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
  117.                         verifyCode.append((char)t);  
  118.                         i++;  
  119.                     }  
  120.                 }  
  121.             break;  
  122.             case TYPE_ALL_MIXED:  
  123.                 while(i < length){  
  124.                     int t = random.nextInt(123);  
  125.                     if((t>=97 || (t>=65&&t<=90) || (t>=48&&t<=57)) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
  126.                         verifyCode.append((char)t);  
  127.                         i++;  
  128.                     }  
  129.                 }  
  130.             break;  
  131.             case TYPE_NUM_UPPER:  
  132.                 while(i < length){  
  133.                     int t = random.nextInt(91);  
  134.                     if((t>=65 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){  
  135.                         verifyCode.append((char)t);  
  136.                         i++;  
  137.                     }  
  138.                 }  
  139.             break;  
  140.             case TYPE_NUM_LOWER:  
  141.                 while(i < length){  
  142.                     int t = random.nextInt(123);  
  143.                     if((t>=97 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){  
  144.                         verifyCode.append((char)t);  
  145.                         i++;  
  146.                     }  
  147.                 }  
  148.             break;  
  149.             case TYPE_UPPER_ONLY:  
  150.                 while(i < length){  
  151.                     int t = random.nextInt(91);  
  152.                     if((t >= 65) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
  153.                         verifyCode.append((char)t);  
  154.                         i++;  
  155.                     }  
  156.                 }  
  157.             break;  
  158.             case TYPE_LOWER_ONLY:  
  159.                 while(i < length){  
  160.                     int t = random.nextInt(123);  
  161.                     if((t>=97) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
  162.                         verifyCode.append((char)t);  
  163.                         i++;  
  164.                     }  
  165.                 }  
  166.             break;  
  167.         }  
  168.         return verifyCode.toString();  
  169.     }  
  170.   
  171.     /** 
  172.      * 已有驗證碼,生成驗證碼圖片 
  173.      * @param textCode       文本驗證碼 
  174.      * @param width          圖片寬度(注意此寬度若過小,容易造成驗證碼文本顯示不全,如4個字符的文本可使用85到90的寬度) 
  175.      * @param height         圖片高度 
  176.      * @param interLine      圖片中干擾線的條數 
  177.      * @param randomLocation 每個字符的高低位置是否隨機 
  178.      * @param backColor      圖片顏色,若爲null則表示採用隨機顏色 
  179.      * @param foreColor      字體顏色,若爲null則表示採用隨機顏色 
  180.      * @param lineColor      干擾線顏色,若爲null則表示採用隨機顏色 
  181.      * @return 圖片緩存對象 
  182.      */  
  183.     public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){  
  184.         //創建內存圖像  
  185.         BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  186.         //獲取圖形上下文  
  187.         Graphics graphics = bufferedImage.getGraphics();  
  188.         //畫背景圖  
  189.         graphics.setColor(null==backColor ? generateRandomColor() : backColor);  
  190.         graphics.fillRect(00, width, height);  
  191.         //畫干擾線  
  192.         Random random = new Random();  
  193.         if(interLine > 0){  
  194.             int x = 0, y = 0, x1 = width, y1 = 0;  
  195.             for(int i=0; i<interLine; i++){  
  196.                 graphics.setColor(null==lineColor ? generateRandomColor() : lineColor);  
  197.                 y = random.nextInt(height);  
  198.                 y1 = random.nextInt(height);  
  199.                 graphics.drawLine(x, y, x1, y1);  
  200.             }  
  201.         }  
  202.         //字體大小爲圖片高度的80%  
  203.         int fsize = (int)(height * 0.8);  
  204.         int fx = height - fsize;  
  205.         int fy = fsize;  
  206.         //設定字體  
  207.         graphics.setFont(new Font("Default", Font.PLAIN, fsize));  
  208.         //寫驗證碼字符  
  209.         for(int i=0; i<textCode.length(); i++){  
  210.             fy = randomLocation ? (int)((Math.random()*0.3+0.6)*height) : fy;  
  211.             graphics.setColor(null==foreColor ? generateRandomColor() : foreColor);  
  212.             //將驗證碼字符顯示到圖象中  
  213.             graphics.drawString(textCode.charAt(i)+"", fx, fy);  
  214.             fx += fsize * 0.9;  
  215.         }  
  216.         graphics.dispose();  
  217.         return bufferedImage;  
  218.     }  
  219. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章