Shrio登陆验证实例详细解读(转)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 摘要:本文采用了Spring+SpringMVC+Mybatis+Shiro+Msql来写了一个登陆验证的实例,下面来看看过程吧!整个工程基于Mavevn来创建,运行环境为JDK1.6+WIN7+tomcat7.

    摘要:本文采用了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

最终效果如下:

工程整体的目录如下:

java代码如下:

配置文件如下:

页面资源如下:

 

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

准备工作:

先建表:

 

[sql]  view plain  copy
 
  1. drop table if exists user;  
  2.  CREATE TABLE `user` (  
  3.   `id` int(11) primary key auto_increment,  
  4.   `name` varchar(20)  NOT NULL,  
  5.   `age` int(11) DEFAULT NULL,  
  6.   `birthday` date DEFAULT NULL,  
  7.   `password` varchar(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.0</modelVersion>  
  4.     <groupId>com.lin</groupId>  
  5.     <artifactId>ShiroLearn1</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>ShiroLearn1 Maven Webapp</name>  
  9.     <url>http://maven.apache.org</url>  
  10.     <properties>  
  11.         <!-- spring版本号 -->  
  12.         <spring.version>3.2.8.RELEASE</spring.version>  
  13.         <!-- log4j日志文件管理包版本 -->  
  14.         <slf4j.version>1.6.6</slf4j.version>  
  15.         <log4j.version>1.2.12</log4j.version>  
  16.         <!-- junit版本号 -->  
  17.         <junit.version>4.10</junit.version>  
  18.         <!-- mybatis版本号 -->  
  19.         <mybatis.version>3.2.1</mybatis.version>  
  20.     </properties>  
  21.     <dependencies>  
  22.         <!-- 添加Spring依赖 -->  
  23.         <dependency>  
  24.             <groupId>org.springframework</groupId>  
  25.             <artifactId>spring-core</artifactId>  
  26.             <version>${spring.version}</version>  
  27.         </dependency>  
  28.         <dependency>  
  29.             <groupId>org.springframework</groupId>  
  30.             <artifactId>spring-webmvc</artifactId>  
  31.             <version>${spring.version}</version>  
  32.         </dependency>  
  33.         <dependency>  
  34.             <groupId>org.springframework</groupId>  
  35.             <artifactId>spring-context</artifactId>  
  36.             <version>${spring.version}</version>  
  37.         </dependency>  
  38.         <dependency>  
  39.             <groupId>org.springframework</groupId>  
  40.             <artifactId>spring-context-support</artifactId>  
  41.             <version>${spring.version}</version>  
  42.         </dependency>  
  43.         <dependency>  
  44.             <groupId>org.springframework</groupId>  
  45.             <artifactId>spring-aop</artifactId>  
  46.             <version>${spring.version}</version>  
  47.         </dependency>  
  48.         <dependency>  
  49.             <groupId>org.springframework</groupId>  
  50.             <artifactId>spring-aspects</artifactId>  
  51.             <version>${spring.version}</version>  
  52.         </dependency>  
  53.         <dependency>  
  54.             <groupId>org.springframework</groupId>  
  55.             <artifactId>spring-tx</artifactId>  
  56.             <version>${spring.version}</version>  
  57.         </dependency>  
  58.         <dependency>  
  59.             <groupId>org.springframework</groupId>  
  60.             <artifactId>spring-jdbc</artifactId>  
  61.             <version>${spring.version}</version>  
  62.         </dependency>  
  63.         <dependency>  
  64.             <groupId>org.springframework</groupId>  
  65.             <artifactId>spring-web</artifactId>  
  66.             <version>${spring.version}</version>  
  67.         </dependency>  
  68.   
  69.         <!--单元测试依赖 -->  
  70.         <dependency>  
  71.             <groupId>junit</groupId>  
  72.             <artifactId>junit</artifactId>  
  73.             <version>${junit.version}</version>  
  74.             <scope>test</scope>  
  75.         </dependency>  
  76.   
  77.         <!-- 日志文件管理包 -->  
  78.         <!-- log start -->  
  79.         <dependency>  
  80.             <groupId>log4j</groupId>  
  81.             <artifactId>log4j</artifactId>  
  82.             <version>${log4j.version}</version>  
  83.         </dependency>  
  84.         <dependency>  
  85.             <groupId>org.slf4j</groupId>  
  86.             <artifactId>slf4j-api</artifactId>  
  87.             <version>${slf4j.version}</version>  
  88.         </dependency>  
  89.         <dependency>  
  90.             <groupId>org.slf4j</groupId>  
  91.             <artifactId>slf4j-log4j12</artifactId>  
  92.             <version>${slf4j.version}</version>  
  93.         </dependency>  
  94.         <!-- log end -->  
  95.   
  96.         <!--spring单元测试依赖 -->  
  97.         <dependency>  
  98.             <groupId>org.springframework</groupId>  
  99.             <artifactId>spring-test</artifactId>  
  100.             <version>${spring.version}</version>  
  101.             <scope>test</scope>  
  102.         </dependency>  
  103.   
  104.         <!--mybatis依赖 -->  
  105.         <dependency>  
  106.             <groupId>org.mybatis</groupId>  
  107.             <artifactId>mybatis</artifactId>  
  108.             <version>${mybatis.version}</version>  
  109.         </dependency>  
  110.   
  111.         <!-- mybatis/spring包 -->  
  112.         <dependency>  
  113.             <groupId>org.mybatis</groupId>  
  114.             <artifactId>mybatis-spring</artifactId>  
  115.             <version>1.2.0</version>  
  116.         </dependency>  
  117.   
  118.         <!-- mysql驱动包 -->  
  119.         <dependency>  
  120.             <groupId>mysql</groupId>  
  121.             <artifactId>mysql-connector-java</artifactId>  
  122.             <version>5.1.29</version>  
  123.         </dependency>  
  124.   
  125.              <!-- servlet驱动包 -->  
  126.         <dependency>  
  127.             <groupId>javax.servlet</groupId>  
  128.             <artifactId>servlet-api</artifactId>  
  129.             <version>3.0-alpha-1</version>  
  130.         </dependency>  
  131.   
  132.         <!-- Spring 整合Shiro需要的依赖 -->  
  133.         <dependency>  
  134.             <groupId>org.apache.shiro</groupId>  
  135.             <artifactId>shiro-core</artifactId>  
  136.             <version>1.2.1</version>  
  137.         </dependency>  
  138.         <dependency>  
  139.             <groupId>org.apache.shiro</groupId>  
  140.             <artifactId>shiro-web</artifactId>  
  141.             <version>1.2.1</version>  
  142.         </dependency>  
  143.         <dependency>  
  144.             <groupId>org.apache.shiro</groupId>  
  145.             <artifactId>shiro-ehcache</artifactId>  
  146.             <version>1.2.1</version>  
  147.         </dependency>  
  148.         <dependency>  
  149.             <groupId>org.apache.shiro</groupId>  
  150.             <artifactId>shiro-spring</artifactId>  
  151.             <version>1.2.1</version>  
  152.         </dependency>  
  153.         <!-- Spring 整合Shiro需要的依赖 -->  
  154.   
  155.     </dependencies>  
  156.     <build>  
  157.         <finalName>ShiroLearn1</finalName>  
  158.         <plugins>  
  159.             <!-- 指定web项目 版本 -->  
  160.             <plugin>  
  161.                 <artifactId>maven-war-plugin</artifactId>  
  162.                 <configuration>  
  163.                     <version>2.4</version>  
  164.                 </configuration>  
  165.             </plugin>  
  166.             <!-- 指定编译使用 -->  
  167.             <plugin>  
  168.                 <groupId>org.apache.maven.plugins</groupId>  
  169.                 <artifactId>maven-compiler-plugin</artifactId>  
  170.                 <version>2.3.2</version>  
  171.                 <configuration>  
  172.                     <source>1.6</source>  
  173.                     <target>1.6</target>  
  174.                 </configuration>  
  175.             </plugin>  
  176.         </plugins>  
  177.     </build>  
  178. </project>  

 

2、自定义Shiro拦截器

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

代码如下:

 

[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<String> roleNames = new HashSet<String>();  
  61.         Set<String> permissions = new HashSet<String>();  
  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<Object, AuthorizationInfo> 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 Configuration</description>  
  9.   
  10.     <!-- Shiro's main business-tier object for web-enabled applications -->  
  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.     <!-- 項目自定义的Realm -->  
  17.     <bean id="shiroDbRealm" class="com.lin.realm.ShiroDbRealm">  
  18.         <property name="cacheManager" ref="cacheManager" />  
  19.     </bean>  
  20.   
  21.     <!-- Shiro Filter -->  
  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.     <!-- 用户授权信息Cache -->  
  39.     <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  
  40.   
  41.     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
  42.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  43.   
  44.     <!-- AOP式方法级权限检查 -->  
  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 Application</display-name>  
  7.     <!-- 起始欢迎界面 -->  
  8.     <welcome-file-list>  
  9.         <welcome-file>/login.do</welcome-file>  
  10.     </welcome-file-list>  
  11.   
  12.     <!-- 读取spring配置文件 -->  
  13.     <context-param>  
  14.         <param-name>contextConfigLocation</param-name>  
  15.         <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>  
  16.     </context-param>  
  17.     <!-- 设计路径变量值 -->  
  18.     <context-param>  
  19.         <param-name>webAppRootKey</param-name>  
  20.         <param-value>springmvc.root</param-value>  
  21.     </context-param>  
  22.   
  23.   
  24.     <!-- Spring字符集过滤器 -->  
  25.     <filter>  
  26.         <filter-name>SpringEncodingFilter</filter-name>  
  27.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  28.         <init-param>  
  29.             <param-name>encoding</param-name>  
  30.             <param-value>UTF-8</param-value>  
  31.         </init-param>  
  32.         <init-param>  
  33.             <param-name>forceEncoding</param-name>  
  34.             <param-value>true</param-value>  
  35.         </init-param>  
  36.     </filter>  
  37.     <filter-mapping>  
  38.         <filter-name>SpringEncodingFilter</filter-name>  
  39.         <url-pattern>/*</url-pattern>  
  40.     </filter-mapping>  
  41.       
  42.     <filter>  
  43.         <filter-name>shiroFilter</filter-name>  
  44.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  45.         <init-param>  
  46.             <param-name>targetFilterLifecycle</param-name>  
  47.             <param-value>true</param-value>  
  48.         </init-param>  
  49.     </filter>  
  50.     <filter-mapping>  
  51.         <filter-name>shiroFilter</filter-name>  
  52.         <url-pattern>/*</url-pattern>  
  53.     </filter-mapping>  
  54.   
  55.     <!-- 日志记录 -->  
  56.     <context-param>  
  57.         <!-- 日志配置文件路径 -->  
  58.         <param-name>log4jConfigLocation</param-name>  
  59.         <param-value>classpath:log4j.properties</param-value>  
  60.     </context-param>  
  61.     <context-param>  
  62.         <!-- 日志页面的刷新间隔 -->  
  63.         <param-name>log4jRefreshInterval</param-name>  
  64.         <param-value>6000</param-value>  
  65.     </context-param>  
  66.     <listener>  
  67.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  68.     </listener>  
  69.   
  70.     <listener>  
  71.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  72.     </listener>  
  73.       
  74.     <!-- 防止spring内存溢出监听器 -->  
  75.     <listener>  
  76.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  77.     </listener>  
  78.   
  79.     <!-- springMVC核心配置 -->  
  80.     <servlet>  
  81.         <servlet-name>dispatcherServlet</servlet-name>  
  82.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  83.         <init-param>  
  84.             <param-name>contextConfigLocation</param-name>  
  85.             <!--spingMVC的配置路径 -->  
  86.             <param-value>classpath:springmvc/spring-mvc.xml</param-value>  
  87.         </init-param>  
  88.         <load-on-startup>1</load-on-startup>  
  89.     </servlet>  
  90.     <!-- 拦截设置 -->  
  91.     <servlet-mapping>  
  92.         <servlet-name>dispatcherServlet</servlet-name>  
  93.         <url-pattern>/</url-pattern>  
  94.     </servlet-mapping>  
  95.   
  96.     <!-- 配置session超时时间,单位分钟 -->  
  97.     <session-config>  
  98.         <session-timeout>15</session-timeout>  
  99.     </session-config>  
  100.     <error-page>  
  101.         <error-code>404</error-code>  
  102.         <location>/WEB-INF/views/error/404.jsp</location>  
  103.     </error-page>  
  104.     <error-page>  
  105.         <error-code>401</error-code>  
  106.         <location>/WEB-INF/views/error/401.jsp</location>  
  107.     </error-page>  
  108. </web-app>  

 

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

5、登陆页面login.jsp

以下是默认登陆的界面

 

[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. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  10. <html>  
  11. <head>  
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  13. <title>Insert title here</title>  
  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. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  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><href="${ctx}/logout.html">退出</a>  
  19.     <p>一、验证当前用户是否为"访客",即未认证(包含未记住)的用户</p>  
  20.     <shiro:guest>    
  21.         Hi there!  Please <href="login.jsp">Login</a> or <href="signup.jsp">Signup</a> today!    
  22.     </shiro:guest>  
  23.     <p>二、认证通过或已记住的用户</p>  
  24.     <shiro:user>    
  25.         Welcome back John!  Not John? Click <href="login.jsp">here<a> to login.   
  26.     </shiro:user>  
  27.     <p>三、已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。</p>  
  28.     <shiro:authenticated>    
  29.         <href="updateAccount.jsp">Update your contact information</a>.    
  30.     </shiro:authenticated>  
  31.     <p>四、未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。</p>  
  32.     <shiro:notAuthenticated>    
  33.         Please <href="login.jsp">login</a> 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.         <href="admin.jsp">Administer the system</a>    
  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. }  

再来看看效果吧!

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

 

http://blog.csdn.net/evankaka/article/details/50196003

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
Shrio配置多个Realm、SecurityManager认证策略
Shrio配置多个Realm、SecurityManager认证策略
|
6月前
|
Java
08 Shrio 授权的三种方式
08 Shrio 授权的三种方式
25 1
|
6月前
|
Java 数据安全/隐私保护
07 Shrio 授权的几个关键对象
07 Shrio 授权的几个关键对象
24 1
|
6月前
|
存储 Java 测试技术
03 Shrio身份认证示例
03 Shrio身份认证示例
20 0
|
6月前
|
API 数据安全/隐私保护
06 Shrio Authenticator及AuthenticationStrategy
06 Shrio Authenticator及AuthenticationStrategy
20 1
|
8月前
|
安全 搜索推荐 Java
SpringSecurity-8-自动登录和注销功能实现
当我们在登录某一个网站的时候,我们会使用账号密码进行登录,但是我们不想每一次关闭浏览器,我们不想每一次重新输入账号和密码,贴合用户的登录体验,给用户带来方便,我们使用自动登录功能,将登录信息保存在浏览器的cookie中,这样用户在下次访问的时候,自动实现校验并新建登录状态。但是这样也会给用户带来信息泄露的危险。
92 0
|
8月前
|
JSON 安全 搜索推荐
​SpringSecurity-5-自定义登录验证
​SpringSecurity-5-自定义登录验证
96 0
|
8月前
|
缓存 数据安全/隐私保护
SpringSecurity-11-只允许一个用户登录
SpringSecurity-11-只允许一个用户登录
328 1
SpringSecurity-11-只允许一个用户登录
|
9月前
|
存储 安全 Java
SpringSecurity基础-简单登录实现
1.SpringSecurity介绍 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
67 0
|
9月前
|
存储 安全 Java
二.SpringSecurity基础-简单登录实现
SpringSecurity基础-简单登录实现