springMVC和Shiro框架整合使用簡單示例
阿新 • • 發佈:2019-01-10
一、目錄結構
首先是目錄結構如圖:
二、pom.xml檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.demo</groupId> <artifactId>ShiroDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ShiroDemo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.9</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-quartz</artifactId> <version>1.2.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.7.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> </dependency> </dependencies> <build> <finalName>ShiroDemo</finalName> </build> </project>
三、applicationCotext.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.gentlehu.shiro"/> <!-- 啟用SpringMVC的註解功能,它會自動註冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關例項 --> <mvc:annotation-driven/> <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證使用者登入的類為自定義的MyRealm.java --> <bean id="myRealm" class="com.gentlehu.shiro.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"/> <!-- anon:它對應的過濾器裡面是空的,什麼都沒做--> <!-- authc:該過濾器下的頁面必須驗證後才能訪問,它是Shiro內建的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter --> <property name="filterChainDefinitions"> <value> /default/login=anon <!-- 任何人都可以訪問,匿名 --> /main**=authc <!-- 需要登入 --> /user/info**=authc <!-- 需要登入 --> /admin/listUser**=authc,perms[admin:manage]<!-- 已經登入並且還要有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> --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
四、MyRealm.java
package com.gentlehu.shiro; 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; public class MyRealm extends AuthorizingRealm { /** * 授權 */ @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { 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 && currentUsername.equals("admin")){ //新增一個角色,不是配置意義上的新增,而是證明該使用者擁有admin角色 simpleAuthorInfo.addRole("admin"); //新增許可權 simpleAuthorInfo.addStringPermission("admin:manage"); System.out.println("已為使用者[admin]賦予了[admin]角色和[admin:manage]許可權"); return simpleAuthorInfo; } return simpleAuthorInfo; //若該方法什麼都不做直接返回null的話,就會導致任何使用者訪問/admin/listUser.jsp時都會自動跳轉到unauthorizedUrl指定的地址 //詳見applicationContext.xml中的<bean id="shiroFilter">的配置 // return null; } /** * 認證 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { //獲取基於使用者名稱和密碼的令牌 //實際上這個authcToken是從LoginController裡面currentUser.login(token)傳過來的 UsernamePasswordToken token = (UsernamePasswordToken)authcToken; System.out.println("MyRealm.doGetAuthenticationInfo.token="+token); // 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("admin".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("admin", "admin", this.getName()); SecurityUtils.getSubject().getSession().setAttribute("currentUser", "admin"); return authcInfo; }else if("user".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("user", "user", this.getName()); SecurityUtils.getSubject().getSession().setAttribute("currentUser", "user"); return authcInfo; } //沒有返回登入使用者名稱對應的SimpleAuthenticationInfo物件時,就會在LoginController中丟擲UnknownAccountException異常 return null; } }
五、DefaultController.java
package com.gentlehu.shiro.controller;
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.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/default")
public class DefaultController {
@RequestMapping("/login")
public String login(String username,String password,Model model){
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
System.out.println("DefaultController.login#token="+token);
Subject currentUser = SecurityUtils.getSubject();
try {
//在呼叫了login方法後,SecurityManager會收到AuthenticationToken,並將其傳送給已配置的Realm執行必須的認證檢查
//每個Realm都能在必要時對提交的AuthenticationTokens作出反應
//所以這一步在呼叫login(token)方法時,它會走到MyRealm.doGetAuthenticationInfo()方法中,具體驗證方式詳見此方法
System.out.println("user[" + username + "]do login checking");
currentUser.login(token);
System.out.println("user[" + username + "]authentication success");
}catch(UnknownAccountException uae){
System.out.println("user[" + username + "]UnknownAccountException");
model.addAttribute("error_msg", "UnknownAccountException");
}catch(IncorrectCredentialsException ice){
System.out.println("user[" + username + "]IncorrectCredentialsException");
model.addAttribute("error_msg", "IncorrectCredentialsException");
}catch(LockedAccountException lae){
System.out.println("user[" + username + "]LockedAccountException");
model.addAttribute("error_msg", "LockedAccountException");
}catch(ExcessiveAttemptsException eae){
System.out.println("user[" + username + "]ExcessiveAttemptsException");
model.addAttribute("error_msg", "ExcessiveAttemptsException");
}catch(AuthenticationException ae){
//注意:這個必須放在後面,因為這個異常可以處理所有認證失敗的情況
model.addAttribute("error_msg", "authentication faild");
}
//驗證是否登入成功
if(currentUser.isAuthenticated()){
System.out.println("user[" + username + "]authentication success");
return "main";
}
token.clear();
return "login";
}
@RequestMapping("/logout")
public String logout(){
SecurityUtils.getSubject().logout();
return "redirect:login";
}
}
六、UserController.java
package com.gentlehu.shiro.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/info")
public String info(HttpServletRequest request,Model model){
String currentUser = (String) request.getSession().getAttribute("currentUser");
System.out.println("currentUser"+currentUser);
model.addAttribute("currentUser", currentUser);
return "user/info.jsp";
}
}
七、login.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<body>
<div style="color:red; font-size:22px;">${error_msg}</div>
<form action="login" method="GET">
姓名:<input type="text" name="username"/><br/>
密碼:<input type="text" name="password"/><br/>
<input type="submit" value="確認"/>
</form>
</body>
</html>
八、main.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<body>
普通使用者可訪問<a href="/ShiroDemo/user/info.jsp" target="_blank">使用者資訊頁面</a>
<br/>
<br/>
管理員可訪問<a href="/ShiroDemo/admin/listUser.jsp" target="_blank">使用者列表頁面</a>
<br/>
<br/>
<a href="/ShiroDemo/default/logout" target="_blank">Logout</a>
</body>
</html>
九、web.xml
<?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內部固定的 -->
<!-- 通過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的前面 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 例項化Spring容器 -->
<!-- 應用啟動時,該監聽器被執行,它會讀取Spring相關配置檔案 -->
<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>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Session超時20分鐘(零或負數表示會話永不超時) -->
<!--
<session-config>
<session-timeout>20</session-timeout>
</session-config>
-->
<error-page>
<!-- 401表示許可權被拒絕 -->
<error-code>401</error-code>
<location>/401.jsp</location>
</error-page>
<error-page>
<error-code>405</error-code>
<location>/405.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
</web-app>
其他頁面沒什麼內容。就是顯示我是哪個介面。 整體過程就是準備好這些檔案之後,maven install . Run As MyEclipse Server Application. 然後訪問 http://localhost:8080/ShiroDemo/login.jsp 沒有登入的使用者只能訪問login.jsp.訪問其他頁面會報401錯誤。