shiro配置及配置项说明

阅读更多

    摘要:本文采用了Spring+SpringMVC+Mybatis+Shiro+Msql来写了一个登陆验证的实例,下面来看看过程吧!整个工程基于Mavevn来创建,运行环境为JDK1.6+WIN7+tomcat7.

这里主要说了Shiro的搭建过程,Spring+SpringMVC+Mybatis的搭建过可以看这里Spring+Mybatis+SpringMVC+Maven+MySql搭建实例

整体工程免费下载:http://download.csdn.net/detail/evankaka/9331135

最终效果如下:

shiro配置及配置项说明_第1张图片

工程整体的目录如下:

java代码如下:

shiro配置及配置项说明_第2张图片

配置文件如下:

shiro配置及配置项说明_第3张图片

页面资源如下:

shiro配置及配置项说明_第4张图片

 

好了,下面来简单说下过程吧!

准备工作:

先建表:

 

[sql]  view plain  copy
 
  1. drop table if exists user;  
  2.  CREATE TABLE `user` (  
  3.   `id` int(11) primary key auto_increment,  
  4.   `namevarchar(20)  NOT NULL,  
  5.   `age` int(11) DEFAULT NULL,  
  6.   `birthday` date DEFAULT NULL,  
  7.   `passwordvarchar(20)  NOT NULL  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  9.   
  10.  insert into user values(1,'lin',12,'2013-12-01','123456');  
  11.  insert into user values(2,'apple',34,'1999-12-01','123456');  
  12.  insert into user values(3,'evankaka',23,'2017-12-01','123456');  


建好后,新建一个Maven的webApp的工程,记得把结构设置成上面的那样!

 

下面来看看一些代码和配置

1、POM文件

注意不要少导包了,如果项目出现红叉,一般都是JDK版本的设置问题,自己百度一下就可以解决

 

[html]  view plain  copy
 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0modelVersion>  
  4.     <groupId>com.lingroupId>  
  5.     <artifactId>ShiroLearn1artifactId>  
  6.     <packaging>warpackaging>  
  7.     <version>0.0.1-SNAPSHOTversion>  
  8.     <name>ShiroLearn1 Maven Webappname>  
  9.     <url>http://maven.apache.orgurl>  
  10.     <properties>  
  11.           
  12.         <spring.version>3.2.8.RELEASEspring.version>  
  13.           
  14.         <slf4j.version>1.6.6slf4j.version>  
  15.         <log4j.version>1.2.12log4j.version>  
  16.           
  17.         <junit.version>4.10junit.version>  
  18.           
  19.         <mybatis.version>3.2.1mybatis.version>  
  20.     properties>  
  21.     <dependencies>  
  22.           
  23.         <dependency>  
  24.             <groupId>org.springframeworkgroupId>  
  25.             <artifactId>spring-coreartifactId>  
  26.             <version>${spring.version}version>  
  27.         dependency>  
  28.         <dependency>  
  29.             <groupId>org.springframeworkgroupId>  
  30.             <artifactId>spring-webmvcartifactId>  
  31.             <version>${spring.version}version>  
  32.         dependency>  
  33.         <dependency>  
  34.             <groupId>org.springframeworkgroupId>  
  35.             <artifactId>spring-contextartifactId>  
  36.             <version>${spring.version}version>  
  37.         dependency>  
  38.         <dependency>  
  39.             <groupId>org.springframeworkgroupId>  
  40.             <artifactId>spring-context-supportartifactId>  
  41.             <version>${spring.version}version>  
  42.         dependency>  
  43.         <dependency>  
  44.             <groupId>org.springframeworkgroupId>  
  45.             <artifactId>spring-aopartifactId>  
  46.             <version>${spring.version}version>  
  47.         dependency>  
  48.         <dependency>  
  49.             <groupId>org.springframeworkgroupId>  
  50.             <artifactId>spring-aspectsartifactId>  
  51.             <version>${spring.version}version>  
  52.         dependency>  
  53.         <dependency>  
  54.             <groupId>org.springframeworkgroupId>  
  55.             <artifactId>spring-txartifactId>  
  56.             <version>${spring.version}version>  
  57.         dependency>  
  58.         <dependency>  
  59.             <groupId>org.springframeworkgroupId>  
  60.             <artifactId>spring-jdbcartifactId>  
  61.             <version>${spring.version}version>  
  62.         dependency>  
  63.         <dependency>  
  64.             <groupId>org.springframeworkgroupId>  
  65.             <artifactId>spring-webartifactId>  
  66.             <version>${spring.version}version>  
  67.         dependency>  
  68.   
  69.           
  70.         <dependency>  
  71.             <groupId>junitgroupId>  
  72.             <artifactId>junitartifactId>  
  73.             <version>${junit.version}version>  
  74.             <scope>testscope>  
  75.         dependency>  
  76.   
  77.           
  78.           
  79.         <dependency>  
  80.             <groupId>log4jgroupId>  
  81.             <artifactId>log4jartifactId>  
  82.             <version>${log4j.version}version>  
  83.         dependency>  
  84.         <dependency>  
  85.             <groupId>org.slf4jgroupId>  
  86.             <artifactId>slf4j-apiartifactId>  
  87.             <version>${slf4j.version}version>  
  88.         dependency>  
  89.         <dependency>  
  90.             <groupId>org.slf4jgroupId>  
  91.             <artifactId>slf4j-log4j12artifactId>  
  92.             <version>${slf4j.version}version>  
  93.         dependency>  
  94.           
  95.   
  96.           
  97.         <dependency>  
  98.             <groupId>org.springframeworkgroupId>  
  99.             <artifactId>spring-testartifactId>  
  100.             <version>${spring.version}version>  
  101.             <scope>testscope>  
  102.         dependency>  
  103.   
  104.           
  105.         <dependency>  
  106.             <groupId>org.mybatisgroupId>  
  107.             <artifactId>mybatisartifactId>  
  108.             <version>${mybatis.version}version>  
  109.         dependency>  
  110.   
  111.           
  112.         <dependency>  
  113.             <groupId>org.mybatisgroupId>  
  114.             <artifactId>mybatis-springartifactId>  
  115.             <version>1.2.0version>  
  116.         dependency>  
  117.   
  118.           
  119.         <dependency>  
  120.             <groupId>mysqlgroupId>  
  121.             <artifactId>mysql-connector-javaartifactId>  
  122.             <version>5.1.29version>  
  123.         dependency>  
  124.   
  125.                
  126.         <dependency>  
  127.             <groupId>javax.servletgroupId>  
  128.             <artifactId>servlet-apiartifactId>  
  129.             <version>3.0-alpha-1version>  
  130.         dependency>  
  131.   
  132.           
  133.         <dependency>  
  134.             <groupId>org.apache.shirogroupId>  
  135.             <artifactId>shiro-coreartifactId>  
  136.             <version>1.2.1version>  
  137.         dependency>  
  138.         <dependency>  
  139.             <groupId>org.apache.shirogroupId>  
  140.             <artifactId>shiro-webartifactId>  
  141.             <version>1.2.1version>  
  142.         dependency>  
  143.         <dependency>  
  144.             <groupId>org.apache.shirogroupId>  
  145.             <artifactId>shiro-ehcacheartifactId>  
  146.             <version>1.2.1version>  
  147.         dependency>  
  148.         <dependency>  
  149.             <groupId>org.apache.shirogroupId>  
  150.             <artifactId>shiro-springartifactId>  
  151.             <version>1.2.1version>  
  152.         dependency>  
  153.           
  154.   
  155.     dependencies>  
  156.     <build>  
  157.         <finalName>ShiroLearn1finalName>  
  158.         <plugins>  
  159.               
  160.             <plugin>  
  161.                 <artifactId>maven-war-pluginartifactId>  
  162.                 <configuration>  
  163.                     <version>2.4version>  
  164.                 configuration>  
  165.             plugin>  
  166.               
  167.             <plugin>  
  168.                 <groupId>org.apache.maven.pluginsgroupId>  
  169.                 <artifactId>maven-compiler-pluginartifactId>  
  170.                 <version>2.3.2version>  
  171.                 <configuration>  
  172.                     <source>1.6source>  
  173.                     <target>1.6target>  
  174.                 configuration>  
  175.             plugin>  
  176.         plugins>  
  177.     build>  
  178. project>  

 

2、自定义Shiro拦截器

   这里这个拦截器完成了用户名和密码的验证,验证成功后又给用赋角色和权限(注意,这里赋角色和权限我直接写进去了,没有使用数据库,一般都是要通过service层找到用户名后,再去数据库查该用户对应的角色以及权限,然后再加入到shiro中去)

shiro配置及配置项说明_第5张图片

代码如下:

 

[java]  view plain  copy
 
  1. package com.lin.realm;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  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.cache.Cache;  
  14. import org.apache.shiro.realm.AuthorizingRealm;  
  15. import org.apache.shiro.subject.PrincipalCollection;  
  16. import org.apache.shiro.subject.SimplePrincipalCollection;  
  17. import org.slf4j.Logger;  
  18. import org.slf4j.LoggerFactory;  
  19. import org.springframework.beans.factory.annotation.Autowired;  
  20.   
  21. import com.lin.domain.User;  
  22. import com.lin.service.UserService;  
  23. import com.lin.utils.CipherUtil;  
  24.   
  25. public class ShiroDbRealm extends AuthorizingRealm {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     private static final String ALGORITHM = "MD5";  
  28.       
  29.     @Autowired  
  30.     private UserService userService;  
  31.   
  32.     public ShiroDbRealm() {  
  33.         super();  
  34.     }  
  35.       
  36.     /** 
  37.      * 验证登陆 
  38.      */  
  39.     @Override  
  40.     protected AuthenticationInfo doGetAuthenticationInfo(  
  41.             AuthenticationToken authcToken) throws AuthenticationException {  
  42.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
  43.         System.out.println(token.getUsername());  
  44.         User user = userService.findUserByLoginName(token.getUsername());  
  45.         System.out.println(user);  
  46.         CipherUtil cipher = new CipherUtil();//MD5加密  
  47.         if (user != null) {  
  48.             return new SimpleAuthenticationInfo(user.getName(), cipher.generatePassword(user.getPassword()), getName());  
  49.         }else{  
  50.             throw new AuthenticationException();  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.      * 登陆成功之后,进行角色和权限验证 
  56.      */  
  57.     @Override  
  58.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  59.         /*这里应该根据userName使用role和permission 的serive层来做判断,并将对应 的权限加进来,下面简化了这一步*/  
  60.         Set roleNames = new HashSet();  
  61.         Set permissions = new HashSet();  
  62.         roleNames.add("admin");//添加角色。对应到index.jsp  
  63.         roleNames.add("administrator");  
  64.         permissions.add("create");//添加权限,对应到index.jsp  
  65.         permissions.add("login.do?main");  
  66.         permissions.add("login.do?logout");  
  67.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
  68.         info.setStringPermissions(permissions);  
  69.         return info;  
  70.     }  
  71.   
  72.   
  73.     /** 
  74.      * 清除所有用户授权信息缓存. 
  75.      */  
  76.     public void clearCachedAuthorizationInfo(String principal) {  
  77.         SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());  
  78.         clearCachedAuthorizationInfo(principals);  
  79.     }  
  80.   
  81.   
  82.     /** 
  83.      * 清除所有用户授权信息缓存. 
  84.      */  
  85.     public void clearAllCachedAuthorizationInfo() {  
  86.         Cache cache = getAuthorizationCache();  
  87.         if (cache != null) {  
  88.             for (Object key : cache.keys()) {  
  89.                 cache.remove(key);  
  90.             }  
  91.         }  
  92.     }  
  93.   
  94. //  @PostConstruct  
  95. //  public void initCredentialsMatcher() {//MD5鍔犲瘑  
  96. //      HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);  
  97. //      setCredentialsMatcher(matcher);  
  98. //  }  
  99. }  

3、shiro的配置文件 :spring-shiro.xml

内容如下:

 

[html]  view plain  copy
 
  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.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
  6.     default-lazy-init="true">  
  7.   
  8.     <description>Shiro Configurationdescription>  
  9.   
  10.       
  11.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  12.         <property name="realm" ref="shiroDbRealm" />  
  13.         <property name="cacheManager" ref="cacheManager" />  
  14.     bean>  
  15.   
  16.       
  17.     <bean id="shiroDbRealm" class="com.lin.realm.ShiroDbRealm">  
  18.         <property name="cacheManager" ref="cacheManager" />  
  19.     bean>  
  20.   
  21.       
  22.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  23.         <property name="securityManager" ref="securityManager" />  
  24.         <property name="loginUrl" value="/login.do" />  
  25.         <property name="successUrl" value="/view/index.html" />  
  26.         <property name="unauthorizedUrl" value="/error/noperms.jsp" />  
  27.         <property name="filterChainDefinitions">  
  28.             <value>  
  29.                 /index.html = authc  
  30.                 /checkLogin.do = anon  
  31.                 /login.do = anon  
  32.                 /logout.html = anon  
  33.                 /** = authc  
  34.             value>  
  35.         property>  
  36.     bean>  
  37.   
  38.       
  39.     <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  
  40.   
  41.       
  42.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  43.   
  44.       
  45.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
  46.         depends-on="lifecycleBeanPostProcessor">  
  47.         <property name="proxyTargetClass" value="true" />  
  48.     bean>  
  49.   
  50.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  51.         <property name="securityManager" ref="securityManager" />  
  52.     bean>  
  53. beans>  

 

这里简要说明下:

(1)

securityManager:这个属性是必须的。

loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。

successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。

unauthorizedUrl:没有权限默认跳转的页面。

(2)

anon:例子/admins/**=anon 没有参数,表示可以匿名使用。

authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数

roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。

perms:例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。

rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString

是你访问的url里的?后面的参数。

authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https

user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查

注:anon,authcBasic,auchc,user是认证过滤器,

perms,roles,ssl,rest,port是授权过滤器

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

 

[html]  view plain  copy
 
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.     <display-name>Archetype Created Web Applicationdisplay-name>  
  7.       
  8.     <welcome-file-list>  
  9.         <welcome-file>/login.dowelcome-file>  
  10.     welcome-file-list>  
  11.   
  12.       
  13.     <context-param>  
  14.         <param-name>contextConfigLocationparam-name>  
  15.         <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xmlparam-value>  
  16.     context-param>  
  17.       
  18.     <context-param>  
  19.         <param-name>webAppRootKeyparam-name>  
  20.         <param-value>springmvc.rootparam-value>  
  21.     context-param>  
  22.   
  23.   
  24.       
  25.     <filter>  
  26.         <filter-name>SpringEncodingFilterfilter-name>  
  27.         <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
  28.         <init-param>  
  29.             <param-name>encodingparam-name>  
  30.             <param-value>UTF-8param-value>  
  31.         init-param>  
  32.         <init-param>  
  33.             <param-name>forceEncodingparam-name>  
  34.             <param-value>trueparam-value>  
  35.         init-param>  
  36.     filter>  
  37.     <filter-mapping>  
  38.         <filter-name>SpringEncodingFilterfilter-name>  
  39.         <url-pattern>/*url-pattern>  
  40.     filter-mapping>  
  41.       
  42.     <filter>  
  43.         <filter-name>shiroFilterfilter-name>  
  44.         <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>  
  45.         <init-param>  
  46.             <param-name>targetFilterLifecycleparam-name>  
  47.             <param-value>trueparam-value>  
  48.         init-param>  
  49.     filter>  
  50.     <filter-mapping>  
  51.         <filter-name>shiroFilterfilter-name>  
  52.         <url-pattern>/*url-pattern>  
  53.     filter-mapping>  
  54.   
  55.       
  56.     <context-param>  
  57.           
  58.         <param-name>log4jConfigLocationparam-name>  
  59.         <param-value>classpath:log4j.propertiesparam-value>  
  60.     context-param>  
  61.     <context-param>  
  62.           
  63.         <param-name>log4jRefreshIntervalparam-name>  
  64.         <param-value>6000param-value>  
  65.     context-param>  
  66.     <listener>  
  67.         <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>  
  68.     listener>  
  69.   
  70.     <listener>  
  71.         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  72.     listener>  
  73.       
  74.       
  75.     <listener>  
  76.         <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>  
  77.     listener>  
  78.   
  79.       
  80.     <servlet>  
  81.         <servlet-name>dispatcherServletservlet-name>  
  82.         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
  83.         <init-param>  
  84.             <param-name>contextConfigLocationparam-name>  
  85.               
  86.             <param-value>classpath:springmvc/spring-mvc.xmlparam-value>  
  87.         init-param>  
  88.         <load-on-startup>1load-on-startup>  
  89.     servlet>  
  90.       
  91.     <servlet-mapping>  
  92.         <servlet-name>dispatcherServletservlet-name>  
  93.         <url-pattern>/url-pattern>  
  94.     servlet-mapping>  
  95.   
  96.       
  97.     <session-config>  
  98.         <session-timeout>15session-timeout>  
  99.     session-config>  
  100.     <error-page>  
  101.         <error-code>404error-code>  
  102.         <location>/WEB-INF/views/error/404.jsplocation>  
  103.     error-page>  
  104.     <error-page>  
  105.         <error-code>401error-code>  
  106.         <location>/WEB-INF/views/error/401.jsplocation>  
  107.     error-page>  
  108. web-app>  

 

这里不仅配置了SpringMVC还要配置Shiro!

5、登陆页面login.jsp

以下是默认登陆的界面

shiro配置及配置项说明_第6张图片

 

[html]  view plain  copy
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>  
  2. <%  
  3.     String url = request.getRequestURL().toString();  
  4.     url = url.substring(0, url.indexOf('/', url.indexOf("//") + 2));  
  5.     String context = request.getContextPath();  
  6.     url += context;  
  7.     application.setAttribute("ctx", url);  
  8. %>  
  9. >  
  10. <html>  
  11. <head>  
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  13. <title>Insert title heretitle>  
  14. head>  
  15. <body>  
  16.     <form action="${ctx}/checkLogin.do" method="post">  
  17.         username: <input type="text" name="username"><br>  
  18.         password: <input type="password" name="password"><br>  
  19.         <input type="submit" value="登录">  
  20.     form>  
  21. body>  
  22. html>  

 

6、验证成功页面index.jsp

如果用户名和密码正确后,跳转到的页面

 

[html]  view plain  copy
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>  
  4. <%  
  5.     String url = request.getRequestURL().toString();  
  6.     url = url.substring(0, url.indexOf('/', url.indexOf("//") + 2));  
  7.     String context = request.getContextPath();  
  8.     url += context;  
  9.     application.setAttribute("ctx", url);  
  10. %>  
  11. >  
  12. <html>  
  13. <head>  
  14. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  15. <title>Shiro登陆实例title>  
  16. head>  
  17. <body>  
  18.     <h1>Shiro登陆实例h1><a href="${ctx}/logout.html">退出a>  
  19.     <p>一、验证当前用户是否为"访客",即未认证(包含未记住)的用户p>  
  20.     <shiro:guest>    
  21.         Hi there!  Please <a href="login.jsp">Logina> or <a href="signup.jsp">Signupa> today!    
  22.     shiro:guest>  
  23.     <p>二、认证通过或已记住的用户p>  
  24.     <shiro:user>    
  25.         Welcome back John!  Not John? Click <a href="login.jsp">here<a> to login.   
  26.     shiro:user>  
  27.     <p>三、已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。p>  
  28.     <shiro:authenticated>    
  29.         <a href="updateAccount.jsp">Update your contact informationa>.    
  30.     shiro:authenticated>  
  31.     <p>四、未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。p>  
  32.     <shiro:notAuthenticated>    
  33.         Please <a href="login.jsp">logina> in order to update your credit card information.    
  34.     shiro:notAuthenticated>    
  35.     <p>五、输出当前用户信息,通常为登录帐号信息p>  
  36.     Hello, <shiro:principal/>, how are you today?    
  37.     <p>六、验证当前用户是否属于该角色p>  
  38.     <shiro:hasRole name="administrator">    
  39.         <a href="admin.jsp">Administer the systema>    
  40.     shiro:hasRole>    
  41.     <p>七、与hasRole标签逻辑相反,当用户不属于该角色时验证通过p>  
  42.     <shiro:lacksRole name="administrator">    
  43.         Sorry, you are not allowed to administer the system.    
  44.     shiro:lacksRole>    
  45.     <p>八、验证当前用户是否属于以下任意一个角色。p>  
  46.     <shiro:hasAnyRoles name="developer,manager,administrator">  
  47.         You are either a developer,manager, or administrator.    
  48.     shiro:hasAnyRoles>  
  49.    <p>九、验证当前用户权限。p>  
  50.     <shiro:hasPermission name="create">    
  51.       <p>当前用户拥有增加的权限!!!!!!!!!!!!!p>  
  52.     shiro:hasPermission>    
  53.   
  54.     <shiro:hasPermission name="delete">    
  55.        <p>当前用户拥有删除的权限!!!!!!!!!!!!!p>  
  56.     shiro:hasPermission>    
  57. body>  
  58. html>  


其它页面就不说了,具体看工程吧!

 

7、controller层来看看

这里/{id}/showUser主要是来验证是否连接成功(现在无法测试了),当然在工程里你也可以到src/test/java里的包com.lin.service下的UserServiceTest.java,那里我也写了一个单元测试的类。

 

[java]  view plain  copy
 
  1. package com.lin.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.shiro.SecurityUtils;  
  7. import org.apache.shiro.authc.UsernamePasswordToken;  
  8. import org.apache.shiro.subject.Subject;  
  9. import org.slf4j.Logger;  
  10. import org.slf4j.LoggerFactory;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.ui.Model;  
  14. import org.springframework.web.bind.annotation.PathVariable;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17. import org.springframework.web.bind.annotation.ResponseBody;  
  18.   
  19. import com.lin.domain.User;  
  20. import com.lin.realm.ShiroDbRealm;  
  21. import com.lin.service.UserService;  
  22. import com.lin.utils.CipherUtil;  
  23.   
  24. @Controller  
  25. public class UserControler {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     @Autowired  
  28.     private UserService userService;  
  29.       
  30.     /** 
  31.      * 验证springmvc与batis连接成功 
  32.      * @param id 
  33.      * @param request 
  34.      * @return 
  35.      */  
  36.     @RequestMapping("/{id}/showUser")  
  37.     public String showUser(@PathVariable int id, HttpServletRequest request) {  
  38.         User user = userService.getUserById(id);  
  39.         System.out.println(user.getName());  
  40.         request.setAttribute("user", user);  
  41.         return "showUser";  
  42.     }  
  43.       
  44.     /** 
  45.      * 初始登陆界面 
  46.      * @param request 
  47.      * @return 
  48.      */  
  49.     @RequestMapping("/login.do")  
  50.     public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
  51.         logger.debug("来自IP[" + request.getRemoteHost() + "]的访问");  
  52.         return "login";  
  53.     }  
  54.       
  55.     /** 
  56.      * 验证用户名和密码 
  57.      * @param request 
  58.      * @return 
  59.      */  
  60.     @RequestMapping("/checkLogin.do")  
  61.     public String login(HttpServletRequest request) {  
  62.         String result = "login.do";  
  63.         // 取得用户名  
  64.         String username = request.getParameter("username");  
  65.         //取得 密码,并用MD5加密  
  66.         String password = CipherUtil.generatePassword(request.getParameter("password"));  
  67.         //String password = request.getParameter("password");  
  68.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  69.           
  70.         Subject currentUser = SecurityUtils.getSubject();  
  71.         try {  
  72.             System.out.println("----------------------------");  
  73.             if (!currentUser.isAuthenticated()){//使用shiro来验证  
  74.                 token.setRememberMe(true);  
  75.                 currentUser.login(token);//验证角色和权限  
  76.             }  
  77.             System.out.println("result: " + result);  
  78.             result = "index";//验证成功  
  79.         } catch (Exception e) {  
  80.             logger.error(e.getMessage());  
  81.             result = "login。do";//验证失败  
  82.         }  
  83.         return result;  
  84.     }  
  85.     
  86.     /** 
  87.      * 退出 
  88.      * @return 
  89.      */  
  90.     @RequestMapping(value = "/logout")    
  91.     @ResponseBody    
  92.     public String logout() {    
  93.     
  94.         Subject currentUser = SecurityUtils.getSubject();    
  95.         String result = "logout";    
  96.         currentUser.logout();    
  97.         return result;    
  98.     }    
  99.        
  100. }  

再来看看效果吧!

shiro配置及配置项说明_第7张图片

你可能感兴趣的:(shiro)