天天看點

SpringMVC整合Shiro

這裡用的是SpringMVC-3.2.4和Shiro-1.2.2:

首先是web.xml

<span style="color:#663366;"><?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">  
    <!-- 指定Spring的配置檔案 -->  
    <!-- 否則Spring會預設從WEB-INF下尋找配置檔案,contextConfigLocation屬性是Spring内部固定的 -->  
    <!-- 通過ContextLoaderListener的父類ContextLoader的第120行發現CONFIG_LOCATION_PARAM固定為contextConfigLocation -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:applicationContext.xml</param-value>  
    </context-param>  
  
    <!-- 防止發生java.beans.Introspector記憶體洩露,應将它配置在ContextLoaderListener的前面 -->  
    <!-- 較長的描述見http://blog.csdn.net/jadyer/article/details/11991457 -->  
    <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>  
  
    <!-- 解決亂碼問題 -->  
    <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:applicationContext.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
  
    <!-- 預設歡迎頁 -->  
    <!-- 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>  
        <error-code>java.lang.Throwable</error-code>  
        <location>/WEB-INF/500.jsp</location>  
    </error-page>  
</web-app></span>           

下面是用于顯示Request

method 'GET' not supported的//WebRoot//WEB-INF//405.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
    <head>  
        <title>405.html</title>  
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
    </head>  
    <body>  
        <font color="blue">  
            Request method 'GET' not supported  
            <br/><br/>  
            The specified HTTP method is not allowed for the requested resource.  
        </font>  
    </body>  
</html>            

下面是允許匿名使用者通路的//WebRoot//login.jsp:

<%@ page language="java" pageEncoding="UTF-8"%>  
  
<script type="text/javascript">  
<!--  
function reloadVerifyCode(){  
    document.getElementById('verifyCodeImage').setAttribute('src', '${pageContext.request.contextPath}/mydemo/getVerifyCodeImage');  
}  
//-->  
</script>  
  
<div style="color:red; font-size:22px;">${message_login}</div>  
  
<form action="<%=request.getContextPath()%>/mydemo/login" method="POST">  
    姓名:<input type="text" name="username"/><br/>  
    密碼:<input type="text" name="password"/><br/>  
    驗證:<input type="text" name="verifyCode"/>  
             
         <img id="verifyCodeImage" onclick="reloadVerifyCode()" src="<%=request.getContextPath()%>/mydemo/getVerifyCodeImage"/><br/>  
    <input type="submit" value="确認"/>  
</form>            

下面是使用者登入後顯示的//WebRoot//main.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
    普通使用者可通路<a href="<%=request.getContextPath()%>/mydemo/getUserInfo" target="_blank">使用者資訊頁面</a>  
    <br/>  
    <br/>  
    管理者可通路<a href="<%=request.getContextPath()%>/admin/listUser.jsp" target="_blank">使用者清單頁面</a>  
    <br/>  
    <br/>  
    <a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>             

下面是隻有管理者才允許通路的//WebRoot//admin//listUser.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
This is listUser.jsp  
<br/>  
<br/>  
<a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>            

下面是普通的登入使用者所允許通路的//WebRoot//user//info.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
    目前登入的使用者為${currUser}  
    <br/>  
    <br/>  
    <a href="<%=request.getContextPath()%>/mydemo/logout" target="_blank">Logout</a>             

下面是//src//log4j.properties

#use Root for GobalConfig  
    log4j.rootLogger=DEBUG,CONSOLE  
      
    log4j.logger.java.sql=DEBUG  
    log4j.logger.org.apache.shiro=DEBUG  
    log4j.logger.org.apache.commons=DEBUG  
    log4j.logger.org.springframework=DEBUG  
      
    #use ConsoleAppender for ConsoleOut  
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  
    log4j.appender.CONSOLE.Threshold=DEBUG  
    log4j.appender.CONSOLE.Target=System.out  
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  
    log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyyMMdd HH:mm:ss}][%t][%C{1}.%M]%m%n             

下面是//src//applicationContext.xml

<?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.jadyer"/>  
      
    <!-- 啟用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>  
  
    <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證使用者登入的類為自定義的ShiroDbRealm.java -->  
    <bean id="myRealm" class="com.jadyer.realm.MyRealm"/>  
  
    <!-- 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"/>  
    </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>            

下面是自定義的Realm類----MyRealm.java

package com.jadyer.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個使用者:jadyer和玄玉,jadyer具有admin角色和admin:manage權限,玄玉不具有任何角色和權限 
 * @create Sep 29, 2013 3:15:31 PM 
 * @author 玄玉<http://blog.csdn.net/jadyer> 
 */  
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 && "jadyer".equals(currentUsername)){  
            //添加一個角色,不是配置意義上的添加,而是證明該使用者擁有admin角色    
            simpleAuthorInfo.addRole("admin");  
            //添權重限  
            simpleAuthorInfo.addStringPermission("admin:manage");  
            System.out.println("已為使用者[jadyer]賦予了[admin]角色和[admin:manage]權限");  
            return simpleAuthorInfo;  
        }else if(null!=currentUsername && "玄玉".equals(currentUsername)){  
            System.out.println("目前使用者[玄玉]無授權");  
            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("jadyer".equals(token.getUsername())){  
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("jadyer", "jadyer", this.getName());  
            this.setSession("currentUser", "jadyer");  
            return authcInfo;  
        }else if("玄玉".equals(token.getUsername())){  
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("玄玉", "xuanyu", this.getName());  
            this.setSession("currentUser", "玄玉");  
            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

package com.jadyer.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;  
      
    import com.jadyer.util.VerifyCodeUtil;  
      
    /** 
     * 本例中用到的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 
     * @author 玄玉<http://blog.csdn.net/jadyer> 
     */  
    @Controller  
    @RequestMapping("mydemo")  
    public class LoginController {  
        /** 
         * 擷取驗證碼圖檔和文本(驗證碼文本會儲存在HttpSession中) 
         */  
        @RequestMapping("/getVerifyCodeImage")  
        public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {  
            //設定頁面不緩存  
            response.setHeader("Pragma", "no-cache");  
            response.setHeader("Cache-Control", "no-cache");  
            response.setDateHeader("Expires", 0);  
            String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);  
            //将驗證碼放到HttpSession裡面  
            request.getSession().setAttribute("verifyCode", verifyCode);  
            System.out.println("本次生成的驗證碼為[" + verifyCode + "],已存放到HttpSession中");  
            //設定輸出的内容的類型為JPEG圖像  
            response.setContentType("image/jpeg");  
            BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);  
            //寫給浏覽器  
            ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());  
        }  
          
          
        /** 
         * 使用者登入 
         */  
        @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");  
            //擷取HttpSession中的驗證碼  
            String verifyCode = (String)request.getSession().getAttribute("verifyCode");  
            //擷取使用者請求表單中輸入的驗證碼  
            String submitCode = WebUtils.getCleanParam(request, "verifyCode");  
            System.out.println("使用者[" + username + "]登入時輸入的驗證碼為[" + submitCode + "],HttpSession中的驗證碼為[" + verifyCode + "]");  
            if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){  
                request.setAttribute("message_login", "驗證碼不正确");  
                return resultPageURL;  
            }  
            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.jadyer.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";  
        }  
    }             

最後是用于生成登入驗證碼的VerifyCodeUtil.java

<span style="color:#330033;">    package com.jadyer.util;  
      
    import java.awt.Color;  
    import java.awt.Font;  
    import java.awt.Graphics;  
    import java.awt.image.BufferedImage;  
    import java.util.Random;  
      
    /** 
     * 驗證碼生成器 
     * @see -------------------------------------------------------------------------------------------------------------- 
     * @see 可生成數字、大寫、小寫字母及三者混合類型的驗證碼 
     * @see 支援自定義驗證碼字元數量,支援自定義驗證碼圖檔的大小,支援自定義需排除的特殊字元,支援自定義幹擾線的數量,支援自定義驗證碼圖文顔色 
     * @see -------------------------------------------------------------------------------------------------------------- 
     * @see 另外,給Shiro加入驗證碼有多種方式,也可以通過繼承修改FormAuthenticationFilter類,通過Shiro去驗證驗證碼 
     * @see 而這裡既然使用了SpringMVC,也為了簡化操作,就使用此工具生成驗證碼,并在Controller中處理驗證碼的校驗 
     * @see -------------------------------------------------------------------------------------------------------------- 
     * @create Sep 29, 2013 4:23:13 PM 
     * @author 玄玉<http://blog.csdn.net/jadyer> 
     */  
    public class VerifyCodeUtil {  
        /** 
         * 驗證碼類型為僅數字,即0~9 
         */  
        public static final int TYPE_NUM_ONLY = 0;  
      
        /** 
         * 驗證碼類型為僅字母,即大小寫字母混合 
         */  
        public static final int TYPE_LETTER_ONLY = 1;  
      
        /** 
         * 驗證碼類型為數字和大小寫字母混合 
         */  
        public static final int TYPE_ALL_MIXED = 2;  
      
        /** 
         * 驗證碼類型為數字和大寫字母混合 
         */  
        public static final int TYPE_NUM_UPPER = 3;  
      
        /** 
         * 驗證碼類型為數字和小寫字母混合 
         */  
        public static final int TYPE_NUM_LOWER = 4;  
      
        /** 
         * 驗證碼類型為僅大寫字母 
         */  
        public static final int TYPE_UPPER_ONLY = 5;  
      
        /** 
         * 驗證碼類型為僅小寫字母 
         */  
        public static final int TYPE_LOWER_ONLY = 6;  
      
        private VerifyCodeUtil(){}  
          
        /** 
         * 生成随機顔色 
         */  
        private static Color generateRandomColor() {  
            Random random = new Random();  
            return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));  
        }  
          
          
        /** 
         * 生成圖檔驗證碼 
         * @param type           驗證碼類型,參見本類的靜态屬性 
         * @param length         驗證碼字元長度,要求大于0的整數 
         * @param excludeString  需排除的特殊字元 
         * @param width          圖檔寬度(注意此寬度若過小,容易造成驗證碼文本顯示不全,如4個字元的文本可使用85到90的寬度) 
         * @param height         圖檔高度 
         * @param interLine      圖檔中幹擾線的條數 
         * @param randomLocation 每個字元的高低位置是否随機 
         * @param backColor      圖檔顔色,若為null則表示采用随機顔色 
         * @param foreColor      字型顔色,若為null則表示采用随機顔色 
         * @param lineColor      幹擾線顔色,若為null則表示采用随機顔色 
         * @return 圖檔緩存對象 
         */  
        public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){  
            String textCode = generateTextCode(type, length, excludeString);  
            return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor);  
        }  
          
      
        /** 
         * 生成驗證碼字元串 
         * @param type          驗證碼類型,參見本類的靜态屬性 
         * @param length        驗證碼長度,要求大于0的整數 
         * @param excludeString 需排除的特殊字元(無需排除則為null) 
         * @return 驗證碼字元串 
         */  
        public static String generateTextCode(int type, int length, String excludeString){  
            if(length <= 0){  
                return "";  
            }  
            StringBuffer verifyCode = new StringBuffer();  
            int i = 0;  
            Random random = new Random();  
            switch(type){  
                case TYPE_NUM_ONLY:  
                    while(i < length){  
                        int t = random.nextInt(10);  
                        //排除特殊字元  
                        if(null==excludeString || excludeString.indexOf(t+"")<0) {  
                            verifyCode.append(t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_LETTER_ONLY:  
                    while(i < length){  
                        int t = random.nextInt(123);  
                        if((t>=97 || (t>=65&&t<=90)) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_ALL_MIXED:  
                    while(i < length){  
                        int t = random.nextInt(123);  
                        if((t>=97 || (t>=65&&t<=90) || (t>=48&&t<=57)) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_NUM_UPPER:  
                    while(i < length){  
                        int t = random.nextInt(91);  
                        if((t>=65 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_NUM_LOWER:  
                    while(i < length){  
                        int t = random.nextInt(123);  
                        if((t>=97 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_UPPER_ONLY:  
                    while(i < length){  
                        int t = random.nextInt(91);  
                        if((t >= 65) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
                case TYPE_LOWER_ONLY:  
                    while(i < length){  
                        int t = random.nextInt(123);  
                        if((t>=97) && (null==excludeString||excludeString.indexOf((char)t)<0)){  
                            verifyCode.append((char)t);  
                            i++;  
                        }  
                    }  
                break;  
            }  
            return verifyCode.toString();  
        }  
      
        /** 
         * 已有驗證碼,生成驗證碼圖檔 
         * @param textCode       文本驗證碼 
         * @param width          圖檔寬度(注意此寬度若過小,容易造成驗證碼文本顯示不全,如4個字元的文本可使用85到90的寬度) 
         * @param height         圖檔高度 
         * @param interLine      圖檔中幹擾線的條數 
         * @param randomLocation 每個字元的高低位置是否随機 
         * @param backColor      圖檔顔色,若為null則表示采用随機顔色 
         * @param foreColor      字型顔色,若為null則表示采用随機顔色 
         * @param lineColor      幹擾線顔色,若為null則表示采用随機顔色 
         * @return 圖檔緩存對象 
         */  
        public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){  
            //建立記憶體圖像  
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            //擷取圖形上下文  
            Graphics graphics = bufferedImage.getGraphics();  
            //畫背景圖  
            graphics.setColor(null==backColor ? generateRandomColor() : backColor);  
            graphics.fillRect(0, 0, width, height);  
            //畫幹擾線  
            Random random = new Random();  
            if(interLine > 0){  
                int x = 0, y = 0, x1 = width, y1 = 0;  
                for(int i=0; i<interLine; i++){  
                    graphics.setColor(null==lineColor ? generateRandomColor() : lineColor);  
                    y = random.nextInt(height);  
                    y1 = random.nextInt(height);  
                    graphics.drawLine(x, y, x1, y1);  
                }  
            }  
            //字型大小為圖檔高度的80%  
            int fsize = (int)(height * 0.8);  
            int fx = height - fsize;  
            int fy = fsize;  
            //設定字型  
            graphics.setFont(new Font("Default", Font.PLAIN, fsize));  
            //寫驗證碼字元  
            for(int i=0; i<textCode.length(); i++){  
                fy = randomLocation ? (int)((Math.random()*0.3+0.6)*height) : fy;  
                graphics.setColor(null==foreColor ? generateRandomColor() : foreColor);  
                //将驗證碼字元顯示到圖象中  
                graphics.drawString(textCode.charAt(i)+"", fx, fy);  
                fx += fsize * 0.9;  
            }  
            graphics.dispose();  
            return bufferedImage;  
        }  
    }  </span>