日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Shiro学习总结(4)——Shrio登陆验证实例详细解读

發(fā)布時(shí)間:2025/3/15 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Shiro学习总结(4)——Shrio登陆验证实例详细解读 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

最終效果如下:


工程整體的目錄如下:

Java代碼如下:


配置文件如下:


頁面資源如下:



好了,下面來簡單說下過程吧!

準(zhǔn)備工作:

先建表:

[sql]? view plain copy
  • drop?table?if?exists?user;??
  • ?CREATE?TABLE?`user`?(??
  • ??`id`?int(11)?primary?key?auto_increment,??
  • ??`name`?varchar(20)??NOT?NULL,??
  • ??`age`?int(11)?DEFAULT?NULL,??
  • ??`birthday`?date?DEFAULT?NULL,??
  • ??`password`?varchar(20)??NOT?NULL??
  • )?ENGINE=InnoDB?DEFAULT?CHARSET=utf8;??
  • ??
  • ?insert?into?user?values(1,'lin',12,'2013-12-01','123456');??
  • ?insert?into?user?values(2,'apple',34,'1999-12-01','123456');??
  • ?insert?into?user?values(3,'evankaka',23,'2017-12-01','123456');??

  • 建好后,新建一個(gè)Maven的webApp的工程,記得把結(jié)構(gòu)設(shè)置成上面的那樣!

    下面來看看一些代碼和配置

    1、POM文件

    注意不要少導(dǎo)包了,如果項(xiàng)目出現(xiàn)紅叉,一般都是JDK版本的設(shè)置問題,自己百度一下就可以解決

    [html]? view plain copy
  • <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.lin</groupId>??
  • ????<artifactId>ShiroLearn1</artifactId>??
  • ????<packaging>war</packaging>??
  • ????<version>0.0.1-SNAPSHOT</version>??
  • ????<name>ShiroLearn1?Maven?Webapp</name>??
  • ????<url>http://maven.apache.org</url>??
  • ????<properties>??
  • ????????<!--?spring版本號(hào)?-->??
  • ????????<spring.version>3.2.8.RELEASE</spring.version>??
  • ????????<!--?log4j日志文件管理包版本?-->??
  • ????????<slf4j.version>1.6.6</slf4j.version>??
  • ????????<log4j.version>1.2.12</log4j.version>??
  • ????????<!--?junit版本號(hào)?-->??
  • ????????<junit.version>4.10</junit.version>??
  • ????????<!--?mybatis版本號(hào)?-->??
  • ????????<mybatis.version>3.2.1</mybatis.version>??
  • ????</properties>??
  • ????<dependencies>??
  • ????????<!--?添加Spring依賴?-->??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-core</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-webmvc</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-context</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-context-support</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-aop</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-aspects</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-tx</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-jdbc</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-web</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????</dependency>??
  • ??
  • ????????<!--單元測試依賴?-->??
  • ????????<dependency>??
  • ????????????<groupId>junit</groupId>??
  • ????????????<artifactId>junit</artifactId>??
  • ????????????<version>${junit.version}</version>??
  • ????????????<scope>test</scope>??
  • ????????</dependency>??
  • ??
  • ????????<!--?日志文件管理包?-->??
  • ????????<!--?log?start?-->??
  • ????????<dependency>??
  • ????????????<groupId>log4j</groupId>??
  • ????????????<artifactId>log4j</artifactId>??
  • ????????????<version>${log4j.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.slf4j</groupId>??
  • ????????????<artifactId>slf4j-api</artifactId>??
  • ????????????<version>${slf4j.version}</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.slf4j</groupId>??
  • ????????????<artifactId>slf4j-log4j12</artifactId>??
  • ????????????<version>${slf4j.version}</version>??
  • ????????</dependency>??
  • ????????<!--?log?end?-->??
  • ??
  • ????????<!--spring單元測試依賴?-->??
  • ????????<dependency>??
  • ????????????<groupId>org.springframework</groupId>??
  • ????????????<artifactId>spring-test</artifactId>??
  • ????????????<version>${spring.version}</version>??
  • ????????????<scope>test</scope>??
  • ????????</dependency>??
  • ??
  • ????????<!--mybatis依賴?-->??
  • ????????<dependency>??
  • ????????????<groupId>org.mybatis</groupId>??
  • ????????????<artifactId>mybatis</artifactId>??
  • ????????????<version>${mybatis.version}</version>??
  • ????????</dependency>??
  • ??
  • ????????<!--?mybatis/spring包?-->??
  • ????????<dependency>??
  • ????????????<groupId>org.mybatis</groupId>??
  • ????????????<artifactId>mybatis-spring</artifactId>??
  • ????????????<version>1.2.0</version>??
  • ????????</dependency>??
  • ??
  • ????????<!--?mysql驅(qū)動(dòng)包?-->??
  • ????????<dependency>??
  • ????????????<groupId>mysql</groupId>??
  • ????????????<artifactId>mysql-connector-java</artifactId>??
  • ????????????<version>5.1.29</version>??
  • ????????</dependency>??
  • ??
  • ?????????????<!--?servlet驅(qū)動(dòng)包?-->??
  • ????????<dependency>??
  • ????????????<groupId>javax.servlet</groupId>??
  • ????????????<artifactId>servlet-api</artifactId>??
  • ????????????<version>3.0-alpha-1</version>??
  • ????????</dependency>??
  • ??
  • ????????<!--?Spring?整合Shiro需要的依賴?-->??
  • ????????<dependency>??
  • ????????????<groupId>org.apache.shiro</groupId>??
  • ????????????<artifactId>shiro-core</artifactId>??
  • ????????????<version>1.2.1</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.apache.shiro</groupId>??
  • ????????????<artifactId>shiro-web</artifactId>??
  • ????????????<version>1.2.1</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.apache.shiro</groupId>??
  • ????????????<artifactId>shiro-ehcache</artifactId>??
  • ????????????<version>1.2.1</version>??
  • ????????</dependency>??
  • ????????<dependency>??
  • ????????????<groupId>org.apache.shiro</groupId>??
  • ????????????<artifactId>shiro-spring</artifactId>??
  • ????????????<version>1.2.1</version>??
  • ????????</dependency>??
  • ????????<!--?Spring?整合Shiro需要的依賴?-->??
  • ??
  • ????</dependencies>??
  • ????<build>??
  • ????????<finalName>ShiroLearn1</finalName>??
  • ????????<plugins>??
  • ????????????<!--?指定web項(xiàng)目?版本?-->??
  • ????????????<plugin>??
  • ????????????????<artifactId>maven-war-plugin</artifactId>??
  • ????????????????<configuration>??
  • ????????????????????<version>2.4</version>??
  • ????????????????</configuration>??
  • ????????????</plugin>??
  • ????????????<!--?指定編譯使用?-->??
  • ????????????<plugin>??
  • ????????????????<groupId>org.apache.maven.plugins</groupId>??
  • ????????????????<artifactId>maven-compiler-plugin</artifactId>??
  • ????????????????<version>2.3.2</version>??
  • ????????????????<configuration>??
  • ????????????????????<source>1.6</source>??
  • ????????????????????<target>1.6</target>??
  • ????????????????</configuration>??
  • ????????????</plugin>??
  • ????????</plugins>??
  • ????</build>??
  • </project>??

  • 2、自定義Shiro攔截器

    ? ?這里這個(gè)攔截器完成了用戶名和密碼的驗(yàn)證,驗(yàn)證成功后又給用賦角色和權(quán)限(注意,這里賦角色和權(quán)限我直接寫進(jìn)去了,沒有使用數(shù)據(jù)庫,一般都是要通過service層找到用戶名后,再去數(shù)據(jù)庫查該用戶對(duì)應(yīng)的角色以及權(quán)限,然后再加入到shiro中去)


    代碼如下:

    [java]? view plain copy
  • package?com.lin.realm;??
  • ??
  • import?java.util.HashSet;??
  • import?java.util.Set;??
  • ??
  • 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.cache.Cache;??
  • import?org.apache.shiro.realm.AuthorizingRealm;??
  • import?org.apache.shiro.subject.PrincipalCollection;??
  • import?org.apache.shiro.subject.SimplePrincipalCollection;??
  • import?org.slf4j.Logger;??
  • import?org.slf4j.LoggerFactory;??
  • import?org.springframework.beans.factory.annotation.Autowired;??
  • ??
  • import?com.lin.domain.User;??
  • import?com.lin.service.UserService;??
  • import?com.lin.utils.CipherUtil;??
  • ??
  • public?class?ShiroDbRealm?extends?AuthorizingRealm?{??
  • ????private?static?Logger?logger?=?LoggerFactory.getLogger(ShiroDbRealm.class);??
  • ????private?static?final?String?ALGORITHM?=?"MD5";??
  • ??????
  • ????@Autowired??
  • ????private?UserService?userService;??
  • ??
  • ????public?ShiroDbRealm()?{??
  • ????????super();??
  • ????}??
  • ??????
  • ????/**?
  • ?????*?驗(yàn)證登陸?
  • ?????*/??
  • ????@Override??
  • ????protected?AuthenticationInfo?doGetAuthenticationInfo(??
  • ????????????AuthenticationToken?authcToken)?throws?AuthenticationException?{??
  • ????????UsernamePasswordToken?token?=?(UsernamePasswordToken)?authcToken;??
  • ????????System.out.println(token.getUsername());??
  • ????????User?user?=?userService.findUserByLoginName(token.getUsername());??
  • ????????System.out.println(user);??
  • ????????CipherUtil?cipher?=?new?CipherUtil();//MD5加密??
  • ????????if?(user?!=?null)?{??
  • ????????????return?new?SimpleAuthenticationInfo(user.getName(),?cipher.generatePassword(user.getPassword()),?getName());??
  • ????????}else{??
  • ????????????throw?new?AuthenticationException();??
  • ????????}??
  • ????}??
  • ??
  • ????/**?
  • ?????*?登陸成功之后,進(jìn)行角色和權(quán)限驗(yàn)證?
  • ?????*/??
  • ????@Override??
  • ????protected?AuthorizationInfo?doGetAuthorizationInfo(PrincipalCollection?principals)?{??
  • ????????/*這里應(yīng)該根據(jù)userName使用role和permission?的serive層來做判斷,并將對(duì)應(yīng)?的權(quán)限加進(jìn)來,下面簡化了這一步*/??
  • ????????Set<String>?roleNames?=?new?HashSet<String>();??
  • ????????Set<String>?permissions?=?new?HashSet<String>();??
  • ????????roleNames.add("admin");//添加角色。對(duì)應(yīng)到index.jsp??
  • ????????roleNames.add("administrator");??
  • ????????permissions.add("create");//添加權(quán)限,對(duì)應(yīng)到index.jsp??
  • ????????permissions.add("login.do?main");??
  • ????????permissions.add("login.do?logout");??
  • ????????SimpleAuthorizationInfo?info?=?new?SimpleAuthorizationInfo(roleNames);??
  • ????????info.setStringPermissions(permissions);??
  • ????????return?info;??
  • ????}??
  • ??
  • ??
  • ????/**?
  • ?????*?清除所有用戶授權(quán)信息緩存.?
  • ?????*/??
  • ????public?void?clearCachedAuthorizationInfo(String?principal)?{??
  • ????????SimplePrincipalCollection?principals?=?new?SimplePrincipalCollection(principal,?getName());??
  • ????????clearCachedAuthorizationInfo(principals);??
  • ????}??
  • ??
  • ??
  • ????/**?
  • ?????*?清除所有用戶授權(quán)信息緩存.?
  • ?????*/??
  • ????public?void?clearAllCachedAuthorizationInfo()?{??
  • ????????Cache<Object,?AuthorizationInfo>?cache?=?getAuthorizationCache();??
  • ????????if?(cache?!=?null)?{??
  • ????????????for?(Object?key?:?cache.keys())?{??
  • ????????????????cache.remove(key);??
  • ????????????}??
  • ????????}??
  • ????}??
  • ??
  • //??@PostConstruct??
  • //??public?void?initCredentialsMatcher()?{//MD5鍔犲瘑??
  • //??????HashedCredentialsMatcher?matcher?=?new?HashedCredentialsMatcher(ALGORITHM);??
  • //??????setCredentialsMatcher(matcher);??
  • //??}??
  • }??
  • 3、shiro的配置文件 :spring-shiro.xml

    內(nèi)容如下:

    [html]? view plain copy
  • <?xml?version="1.0"?encoding="UTF-8"?>??
  • <beans?xmlns="http://www.springframework.org/schema/beans"??
  • ????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
  • ????xsi:schemaLocation="http://www.springframework.org/schema/beans???
  • ????????????????????????http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"??
  • ????default-lazy-init="true">??
  • ??
  • ????<description>Shiro?Configuration</description>??
  • ??
  • ????<!--?Shiro's?main?business-tier?object?for?web-enabled?applications?-->??
  • ????<bean?id="securityManager"?class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">??
  • ????????<property?name="realm"?ref="shiroDbRealm"?/>??
  • ????????<property?name="cacheManager"?ref="cacheManager"?/>??
  • ????</bean>??
  • ??
  • ????<!--?項(xiàng)目自定義的Realm?-->??
  • ????<bean?id="shiroDbRealm"?class="com.lin.realm.ShiroDbRealm">??
  • ????????<property?name="cacheManager"?ref="cacheManager"?/>??
  • ????</bean>??
  • ??
  • ????<!--?Shiro?Filter?-->??
  • ????<bean?id="shiroFilter"?class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">??
  • ????????<property?name="securityManager"?ref="securityManager"?/>??
  • ????????<property?name="loginUrl"?value="/login.do"?/>??
  • ????????<property?name="successUrl"?value="/view/index.html"?/>??
  • ????????<property?name="unauthorizedUrl"?value="/error/noperms.jsp"?/>??
  • ????????<property?name="filterChainDefinitions">??
  • ????????????<value>??
  • ????????????????/index.html?=?authc??
  • ????????????????/checkLogin.do?=?anon??
  • ????????????????/login.do?=?anon??
  • ????????????????/logout.html?=?anon??
  • ????????????????/**?=?authc??
  • ????????????</value>??
  • ????????</property>??
  • ????</bean>??
  • ??
  • ????<!--?用戶授權(quán)信息Cache?-->??
  • ????<bean?id="cacheManager"?class="org.apache.shiro.cache.MemoryConstrainedCacheManager"?/>??
  • ??
  • ????<!--?保證實(shí)現(xiàn)了Shiro內(nèi)部lifecycle函數(shù)的bean執(zhí)行?-->??
  • ????<bean?id="lifecycleBeanPostProcessor"?class="org.apache.shiro.spring.LifecycleBeanPostProcessor"?/>??
  • ??
  • ????<!--?AOP式方法級(jí)權(quán)限檢查?-->??
  • ????<bean?class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"??
  • ????????depends-on="lifecycleBeanPostProcessor">??
  • ????????<property?name="proxyTargetClass"?value="true"?/>??
  • ????</bean>??
  • ??
  • ????<bean?class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">??
  • ????????<property?name="securityManager"?ref="securityManager"?/>??
  • ????</bean>??
  • </beans>??

  • 這里簡要說明下:

    (1)

    securityManager:這個(gè)屬性是必須的。

    loginUrl:沒有登錄的用戶請(qǐng)求需要登錄的頁面時(shí)自動(dòng)跳轉(zhuǎn)到登錄頁面,不是必須的屬性,不輸入地址的話會(huì)自動(dòng)尋找項(xiàng)目web項(xiàng)目的根目錄下的”/login.jsp”頁面。

    successUrl:登錄成功默認(rèn)跳轉(zhuǎn)頁面,不配置則跳轉(zhuǎn)至”/”。如果登陸前點(diǎn)擊的一個(gè)需要登錄的頁面,則在登錄自動(dòng)跳轉(zhuǎn)到那個(gè)需要登錄的頁面。不跳轉(zhuǎn)到此。

    unauthorizedUrl:沒有權(quán)限默認(rèn)跳轉(zhuǎn)的頁面。

    (2)

    anon:例子/admins/**=anon 沒有參數(shù),表示可以匿名使用。

    authc:例如/admins/user/**=authc表示需要認(rèn)證(登錄)才能使用,沒有參數(shù)

    roles:例子/admins/user/**=roles[admin],參數(shù)可以寫多個(gè),多個(gè)時(shí)必須加上引號(hào),并且參數(shù)之間用逗號(hào)分割,當(dāng)有多個(gè)參數(shù)時(shí),例如admins/user/**=roles["admin,guest"],每個(gè)參數(shù)通過才算通過,相當(dāng)于hasAllRoles()方法。

    perms:例子/admins/user/**=perms[user:add:*],參數(shù)可以寫多個(gè),多個(gè)時(shí)必須加上引號(hào),并且參數(shù)之間用逗號(hào)分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當(dāng)有多個(gè)參數(shù)時(shí)必須每個(gè)參數(shù)都通過才通過,想當(dāng)于isPermitedAll()方法。

    rest:例子/admins/user/**=rest[user],根據(jù)請(qǐng)求的方法,相當(dāng)于/admins/user/**=perms[user:method] ,其中method為post,get,delete等。

    port:例子/admins/user/**=port[8081],當(dāng)請(qǐng)求的url的端口不是8081是跳轉(zhuǎn)到schemal://serverName:8081?queryString,其中schmal是協(xié)議http或https等,serverName是你訪問的host,8081是url配置里port的端口,queryString

    是你訪問的url里的?后面的參數(shù)。

    authcBasic:例如/admins/user/**=authcBasic沒有參數(shù)表示httpBasic認(rèn)證

    ssl:例子/admins/user/**=ssl沒有參數(shù),表示安全的url請(qǐng)求,協(xié)議為https

    user:例如/admins/user/**=user沒有參數(shù)表示必須存在用戶,當(dāng)?shù)侨氩僮鲿r(shí)不做檢查

    注:anon,authcBasic,auchc,user是認(rèn)證過濾器,

    perms,roles,ssl,rest,port是授權(quán)過濾器

    4、web.xml配置解讀shiro的配置文件(上面的)

    [html]? view plain copy
  • <?xml?version="1.0"?encoding="UTF-8"?>??
  • <web-app?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
  • ????xmlns="http://java.sun.com/xml/ns/javaee"?xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"??
  • ????xsi:schemaLocation="http://java.sun.com/xml/ns/javaee?http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"??
  • ????id="WebApp_ID"?version="2.5">??
  • ????<display-name>Archetype?Created?Web?Application</display-name>??
  • ????<!--?起始?xì)g迎界面?-->??
  • ????<welcome-file-list>??
  • ????????<welcome-file>/login.do</welcome-file>??
  • ????</welcome-file-list>??
  • ??
  • ????<!--?讀取spring配置文件?-->??
  • ????<context-param>??
  • ????????<param-name>contextConfigLocation</param-name>??
  • ????????<param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>??
  • ????</context-param>??
  • ????<!--?設(shè)計(jì)路徑變量值?-->??
  • ????<context-param>??
  • ????????<param-name>webAppRootKey</param-name>??
  • ????????<param-value>springmvc.root</param-value>??
  • ????</context-param>??
  • ??
  • ??
  • ????<!--?Spring字符集過濾器?-->??
  • ????<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>??
  • ??????
  • ????<filter>??
  • ????????<filter-name>shiroFilter</filter-name>??
  • ????????<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>??
  • ????????<init-param>??
  • ????????????<param-name>targetFilterLifecycle</param-name>??
  • ????????????<param-value>true</param-value>??
  • ????????</init-param>??
  • ????</filter>??
  • ????<filter-mapping>??
  • ????????<filter-name>shiroFilter</filter-name>??
  • ????????<url-pattern>/*</url-pattern>??
  • ????</filter-mapping>??
  • ??
  • ????<!--?日志記錄?-->??
  • ????<context-param>??
  • ????????<!--?日志配置文件路徑?-->??
  • ????????<param-name>log4jConfigLocation</param-name>??
  • ????????<param-value>classpath:log4j.properties</param-value>??
  • ????</context-param>??
  • ????<context-param>??
  • ????????<!--?日志頁面的刷新間隔?-->??
  • ????????<param-name>log4jRefreshInterval</param-name>??
  • ????????<param-value>6000</param-value>??
  • ????</context-param>??
  • ????<listener>??
  • ????????<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>??
  • ????</listener>??
  • ??
  • ????<listener>??
  • ????????<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>??
  • ????</listener>??
  • ??????
  • ????<!--?防止spring內(nèi)存溢出監(jiān)聽器?-->??
  • ????<listener>??
  • ????????<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>??
  • ????</listener>??
  • ??
  • ????<!--?springMVC核心配置?-->??
  • ????<servlet>??
  • ????????<servlet-name>dispatcherServlet</servlet-name>??
  • ????????<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>??
  • ????????<init-param>??
  • ????????????<param-name>contextConfigLocation</param-name>??
  • ????????????<!--spingMVC的配置路徑?-->??
  • ????????????<param-value>classpath:springmvc/spring-mvc.xml</param-value>??
  • ????????</init-param>??
  • ????????<load-on-startup>1</load-on-startup>??
  • ????</servlet>??
  • ????<!--?攔截設(shè)置?-->??
  • ????<servlet-mapping>??
  • ????????<servlet-name>dispatcherServlet</servlet-name>??
  • ????????<url-pattern>/</url-pattern>??
  • ????</servlet-mapping>??
  • ??
  • ????<!--?配置session超時(shí)時(shí)間,單位分鐘?-->??
  • ????<session-config>??
  • ????????<session-timeout>15</session-timeout>??
  • ????</session-config>??
  • ????<error-page>??
  • ????????<error-code>404</error-code>??
  • ????????<location>/WEB-INF/views/error/404.jsp</location>??
  • ????</error-page>??
  • ????<error-page>??
  • ????????<error-code>401</error-code>??
  • ????????<location>/WEB-INF/views/error/401.jsp</location>??
  • ????</error-page>??
  • </web-app>??

  • 這里不僅配置了SpringMVC還要配置Shiro!

    5、登陸頁面login.jsp

    以下是默認(rèn)登陸的界面


    [html]? view plain copy
  • <%@?page?language="java"?contentType="text/html;?charset=UTF-8"??pageEncoding="UTF-8"%>??
  • <%??
  • ????String?url?=?request.getRequestURL().toString();??
  • ????url?=?url.substring(0,?url.indexOf('/',?url.indexOf("//")?+?2));??
  • ????String?context?=?request.getContextPath();??
  • ????url?+=?context;??
  • ????application.setAttribute("ctx",?url);??
  • %>??
  • <!DOCTYPE?html?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"?"http://www.w3.org/TR/html4/loose.dtd">??
  • <html>??
  • <head>??
  • <meta?http-equiv="Content-Type"?content="text/html;?charset=UTF-8">??
  • <title>Insert?title?here</title>??
  • </head>??
  • <body>??
  • ????<form?action="${ctx}/checkLogin.do"?method="post">??
  • ????????username:?<input?type="text"?name="username"><br>??
  • ????????password:?<input?type="password"?name="password"><br>??
  • ????????<input?type="submit"?value="登錄">??
  • ????</form>??
  • </body>??
  • </html>??

  • 6、驗(yàn)證成功頁面index.jsp

    如果用戶名和密碼正確后,跳轉(zhuǎn)到的頁面

    [html]? view plain copy
  • <%@?page?language="java"?contentType="text/html;?charset=UTF-8"??
  • ????pageEncoding="UTF-8"%>??
  • <%@?taglib?prefix="shiro"?uri="http://shiro.apache.org/tags"%>??
  • <%??
  • ????String?url?=?request.getRequestURL().toString();??
  • ????url?=?url.substring(0,?url.indexOf('/',?url.indexOf("//")?+?2));??
  • ????String?context?=?request.getContextPath();??
  • ????url?+=?context;??
  • ????application.setAttribute("ctx",?url);??
  • %>??
  • <!DOCTYPE?html?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"?"http://www.w3.org/TR/html4/loose.dtd">??
  • <html>??
  • <head>??
  • <meta?http-equiv="Content-Type"?content="text/html;?charset=UTF-8">??
  • <title>Shiro登陸實(shí)例</title>??
  • </head>??
  • <body>??
  • ????<h1>Shiro登陸實(shí)例</h1><a?href="${ctx}/logout.html">退出</a>??
  • ????<p>一、驗(yàn)證當(dāng)前用戶是否為"訪客",即未認(rèn)證(包含未記住)的用戶</p>??
  • ????<shiro:guest>????
  • ????????Hi?there!??Please?<a?href="login.jsp">Login</a>?or?<a?href="signup.jsp">Signup</a>?today!????
  • ????</shiro:guest>??
  • ????<p>二、認(rèn)證通過或已記住的用戶</p>??
  • ????<shiro:user>????
  • ????????Welcome?back?John!??Not?John??Click?<a?href="login.jsp">here<a>?to?login.???
  • ????</shiro:user>??
  • ????<p>三、已認(rèn)證通過的用戶。不包含已記住的用戶,這是與user標(biāo)簽的區(qū)別所在。</p>??
  • ????<shiro:authenticated>????
  • ????????<a?href="updateAccount.jsp">Update?your?contact?information</a>.????
  • ????</shiro:authenticated>??
  • ????<p>四、未認(rèn)證通過用戶,與authenticated標(biāo)簽相對(duì)應(yīng)。與guest標(biāo)簽的區(qū)別是,該標(biāo)簽包含已記住用戶。</p>??
  • ????<shiro:notAuthenticated>????
  • ????????Please?<a?href="login.jsp">login</a>?in?order?to?update?your?credit?card?information.????
  • ????</shiro:notAuthenticated>????
  • ????<p>五、輸出當(dāng)前用戶信息,通常為登錄帳號(hào)信息</p>??
  • ????Hello,?<shiro:principal/>,?how?are?you?today?????
  • ????<p>六、驗(yàn)證當(dāng)前用戶是否屬于該角色</p>??
  • ????<shiro:hasRole?name="administrator">????
  • ????????<a?href="admin.jsp">Administer?the?system</a>????
  • ????</shiro:hasRole>????
  • ????<p>七、與hasRole標(biāo)簽邏輯相反,當(dāng)用戶不屬于該角色時(shí)驗(yàn)證通過</p>??
  • ????<shiro:lacksRole?name="administrator">????
  • ????????Sorry,?you?are?not?allowed?to?administer?the?system.????
  • ????</shiro:lacksRole>????
  • ????<p>八、驗(yàn)證當(dāng)前用戶是否屬于以下任意一個(gè)角色。</p>??
  • ????<shiro:hasAnyRoles?name="developer,manager,administrator">??
  • ????????You?are?either?a?developer,manager,?or?administrator.????
  • ????</shiro:hasAnyRoles>??
  • ???<p>九、驗(yàn)證當(dāng)前用戶權(quán)限。</p>??
  • ????<shiro:hasPermission?name="create">????
  • ??????<p>當(dāng)前用戶擁有增加的權(quán)限!!!!!!!!!!!!!</p>??
  • ????</shiro:hasPermission>????
  • ??
  • ????<shiro:hasPermission?name="delete">????
  • ???????<p>當(dāng)前用戶擁有刪除的權(quán)限!!!!!!!!!!!!!</p>??
  • ????</shiro:hasPermission>????
  • </body>??
  • </html>??

  • 其它頁面就不說了,具體看工程吧!

    7、controller層來看看

    這里/{id}/showUser主要是來驗(yàn)證是否連接成功(現(xiàn)在無法測試了),當(dāng)然在工程里你也可以到src/test/java里的包c(diǎn)om.lin.service下的UserServiceTest.java,那里我也寫了一個(gè)單元測試的類。

    [java]? view plain copy
  • package?com.lin.controller;??
  • ??
  • import?javax.servlet.http.HttpServletRequest;??
  • import?javax.servlet.http.HttpServletResponse;??
  • ??
  • import?org.apache.shiro.SecurityUtils;??
  • import?org.apache.shiro.authc.UsernamePasswordToken;??
  • import?org.apache.shiro.subject.Subject;??
  • import?org.slf4j.Logger;??
  • import?org.slf4j.LoggerFactory;??
  • import?org.springframework.beans.factory.annotation.Autowired;??
  • import?org.springframework.stereotype.Controller;??
  • import?org.springframework.ui.Model;??
  • import?org.springframework.web.bind.annotation.PathVariable;??
  • import?org.springframework.web.bind.annotation.RequestMapping;??
  • import?org.springframework.web.bind.annotation.RequestMethod;??
  • import?org.springframework.web.bind.annotation.ResponseBody;??
  • ??
  • import?com.lin.domain.User;??
  • import?com.lin.realm.ShiroDbRealm;??
  • import?com.lin.service.UserService;??
  • import?com.lin.utils.CipherUtil;??
  • ??
  • @Controller??
  • public?class?UserControler?{??
  • ????private?static?Logger?logger?=?LoggerFactory.getLogger(ShiroDbRealm.class);??
  • ????@Autowired??
  • ????private?UserService?userService;??
  • ??????
  • ????/**?
  • ?????*?驗(yàn)證springmvc與batis連接成功?
  • ?????*?@param?id?
  • ?????*?@param?request?
  • ?????*?@return?
  • ?????*/??
  • ????@RequestMapping("/{id}/showUser")??
  • ????public?String?showUser(@PathVariable?int?id,?HttpServletRequest?request)?{??
  • ????????User?user?=?userService.getUserById(id);??
  • ????????System.out.println(user.getName());??
  • ????????request.setAttribute("user",?user);??
  • ????????return?"showUser";??
  • ????}??
  • ??????
  • ????/**?
  • ?????*?初始登陸界面?
  • ?????*?@param?request?
  • ?????*?@return?
  • ?????*/??
  • ????@RequestMapping("/login.do")??
  • ????public?String?tologin(HttpServletRequest?request,?HttpServletResponse?response,?Model?model){??
  • ????????logger.debug("來自IP["?+?request.getRemoteHost()?+?"]的訪問");??
  • ????????return?"login";??
  • ????}??
  • ??????
  • ????/**?
  • ?????*?驗(yàn)證用戶名和密碼?
  • ?????*?@param?request?
  • ?????*?@return?
  • ?????*/??
  • ????@RequestMapping("/checkLogin.do")??
  • ????public?String?login(HttpServletRequest?request)?{??
  • ????????String?result?=?"login.do";??
  • ????????//?取得用戶名??
  • ????????String?username?=?request.getParameter("username");??
  • ????????//取得?密碼,并用MD5加密??
  • ????????String?password?=?CipherUtil.generatePassword(request.getParameter("password"));??
  • ????????//String?password?=?request.getParameter("password");??
  • ????????UsernamePasswordToken?token?=?new?UsernamePasswordToken(username,?password);??
  • ??????????
  • ????????Subject?currentUser?=?SecurityUtils.getSubject();??
  • ????????try?{??
  • ????????????System.out.println("----------------------------");??
  • ????????????if?(!currentUser.isAuthenticated()){//使用shiro來驗(yàn)證??
  • ????????????????token.setRememberMe(true);??
  • ????????????????currentUser.login(token);//驗(yàn)證角色和權(quán)限??
  • ????????????}??
  • ????????????System.out.println("result:?"?+?result);??
  • ????????????result?=?"index";//驗(yàn)證成功??
  • ????????}?catch?(Exception?e)?{??
  • ????????????logger.error(e.getMessage());??
  • ????????????result?=?"login。do";//驗(yàn)證失敗??
  • ????????}??
  • ????????return?result;??
  • ????}??
  • ????
  • ????/**?
  • ?????*?退出?
  • ?????*?@return?
  • ?????*/??
  • ????@RequestMapping(value?=?"/logout")????
  • ????@ResponseBody????
  • ????public?String?logout()?{????
  • ????
  • ????????Subject?currentUser?=?SecurityUtils.getSubject();????
  • ????????String?result?=?"logout";????
  • ????????currentUser.logout();????
  • ????????return?result;????
  • ????}????
  • ???????
  • }??
  • 再來看看效果吧!

    轉(zhuǎn)載于:https://my.oschina.net/zhanghaiyang/blog/725673

    總結(jié)

    以上是生活随笔為你收集整理的Shiro学习总结(4)——Shrio登陆验证实例详细解读的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。