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

配置文件如下:

页面资源如下:

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

准备工作:

先建表:

  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. insert into user values(1,'lin',12,'2013-12-01','123456');
  10. insert into user values(2,'apple',34,'1999-12-01','123456');
  11. insert into user values(3,'evankaka',23,'2017-12-01','123456');

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

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

1、POM文件

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

  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. <dependency>
  70. <groupId>junit</groupId>
  71. <artifactId>junit</artifactId>
  72. <version>${junit.version}</version>
  73. <scope>test</scope>
  74. </dependency>
  75. <!-- 日志文件管理包 -->
  76. <!-- log start -->
  77. <dependency>
  78. <groupId>log4j</groupId>
  79. <artifactId>log4j</artifactId>
  80. <version>${log4j.version}</version>
  81. </dependency>
  82. <dependency>
  83. <groupId>org.slf4j</groupId>
  84. <artifactId>slf4j-api</artifactId>
  85. <version>${slf4j.version}</version>
  86. </dependency>
  87. <dependency>
  88. <groupId>org.slf4j</groupId>
  89. <artifactId>slf4j-log4j12</artifactId>
  90. <version>${slf4j.version}</version>
  91. </dependency>
  92. <!-- log end -->
  93. <!--spring单元测试依赖 -->
  94. <dependency>
  95. <groupId>org.springframework</groupId>
  96. <artifactId>spring-test</artifactId>
  97. <version>${spring.version}</version>
  98. <scope>test</scope>
  99. </dependency>
  100. <!--mybatis依赖 -->
  101. <dependency>
  102. <groupId>org.mybatis</groupId>
  103. <artifactId>mybatis</artifactId>
  104. <version>${mybatis.version}</version>
  105. </dependency>
  106. <!-- mybatis/spring包 -->
  107. <dependency>
  108. <groupId>org.mybatis</groupId>
  109. <artifactId>mybatis-spring</artifactId>
  110. <version>1.2.0</version>
  111. </dependency>
  112. <!-- mysql驱动包 -->
  113. <dependency>
  114. <groupId>mysql</groupId>
  115. <artifactId>mysql-connector-java</artifactId>
  116. <version>5.1.29</version>
  117. </dependency>
  118. <!-- servlet驱动包 -->
  119. <dependency>
  120. <groupId>javax.servlet</groupId>
  121. <artifactId>servlet-api</artifactId>
  122. <version>3.0-alpha-1</version>
  123. </dependency>
  124. <!-- Spring 整合Shiro需要的依赖 -->
  125. <dependency>
  126. <groupId>org.apache.shiro</groupId>
  127. <artifactId>shiro-core</artifactId>
  128. <version>1.2.1</version>
  129. </dependency>
  130. <dependency>
  131. <groupId>org.apache.shiro</groupId>
  132. <artifactId>shiro-web</artifactId>
  133. <version>1.2.1</version>
  134. </dependency>
  135. <dependency>
  136. <groupId>org.apache.shiro</groupId>
  137. <artifactId>shiro-ehcache</artifactId>
  138. <version>1.2.1</version>
  139. </dependency>
  140. <dependency>
  141. <groupId>org.apache.shiro</groupId>
  142. <artifactId>shiro-spring</artifactId>
  143. <version>1.2.1</version>
  144. </dependency>
  145. <!-- Spring 整合Shiro需要的依赖 -->
  146. </dependencies>
  147. <build>
  148. <finalName>ShiroLearn1</finalName>
  149. <plugins>
  150. <!-- 指定web项目 版本 -->
  151. <plugin>
  152. <artifactId>maven-war-plugin</artifactId>
  153. <configuration>
  154. <version>2.4</version>
  155. </configuration>
  156. </plugin>
  157. <!-- 指定编译使用 -->
  158. <plugin>
  159. <groupId>org.apache.maven.plugins</groupId>
  160. <artifactId>maven-compiler-plugin</artifactId>
  161. <version>2.3.2</version>
  162. <configuration>
  163. <source>1.6</source>
  164. <target>1.6</target>
  165. </configuration>
  166. </plugin>
  167. </plugins>
  168. </build>
  169. </project>

2、自定义Shiro拦截器

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

代码如下:

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

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

内容如下:

  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. <description>Shiro Configuration</description>
  8. <!-- Shiro's main business-tier object for web-enabled applications -->
  9. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  10. <property name="realm" ref="shiroDbRealm" />
  11. <property name="cacheManager" ref="cacheManager" />
  12. </bean>
  13. <!-- 項目自定义的Realm -->
  14. <bean id="shiroDbRealm" class="com.lin.realm.ShiroDbRealm">
  15. <property name="cacheManager" ref="cacheManager" />
  16. </bean>
  17. <!-- Shiro Filter -->
  18. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  19. <property name="securityManager" ref="securityManager" />
  20. <property name="loginUrl" value="/login.do" />
  21. <property name="successUrl" value="/view/index.html" />
  22. <property name="unauthorizedUrl" value="/error/noperms.jsp" />
  23. <property name="filterChainDefinitions">
  24. <value>
  25. /index.html = authc
  26. /checkLogin.do = anon
  27. /login.do = anon
  28. /logout.html = anon
  29. /** = authc
  30. </value>
  31. </property>
  32. </bean>
  33. <!-- 用户授权信息Cache -->
  34. <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
  35. <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
  36. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
  37. <!-- AOP式方法级权限检查 -->
  38. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
  39. depends-on="lifecycleBeanPostProcessor">
  40. <property name="proxyTargetClass" value="true" />
  41. </bean>
  42. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  43. <property name="securityManager" ref="securityManager" />
  44. </bean>
  45. </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的配置文件(上面的)

  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. <!-- 读取spring配置文件 -->
  12. <context-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>
  15. </context-param>
  16. <!-- 设计路径变量值 -->
  17. <context-param>
  18. <param-name>webAppRootKey</param-name>
  19. <param-value>springmvc.root</param-value>
  20. </context-param>
  21. <!-- Spring字符集过滤器 -->
  22. <filter>
  23. <filter-name>SpringEncodingFilter</filter-name>
  24. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  25. <init-param>
  26. <param-name>encoding</param-name>
  27. <param-value>UTF-8</param-value>
  28. </init-param>
  29. <init-param>
  30. <param-name>forceEncoding</param-name>
  31. <param-value>true</param-value>
  32. </init-param>
  33. </filter>
  34. <filter-mapping>
  35. <filter-name>SpringEncodingFilter</filter-name>
  36. <url-pattern>/*</url-pattern>
  37. </filter-mapping>
  38. <filter>
  39. <filter-name>shiroFilter</filter-name>
  40. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  41. <init-param>
  42. <param-name>targetFilterLifecycle</param-name>
  43. <param-value>true</param-value>
  44. </init-param>
  45. </filter>
  46. <filter-mapping>
  47. <filter-name>shiroFilter</filter-name>
  48. <url-pattern>/*</url-pattern>
  49. </filter-mapping>
  50. <!-- 日志记录 -->
  51. <context-param>
  52. <!-- 日志配置文件路径 -->
  53. <param-name>log4jConfigLocation</param-name>
  54. <param-value>classpath:log4j.properties</param-value>
  55. </context-param>
  56. <context-param>
  57. <!-- 日志页面的刷新间隔 -->
  58. <param-name>log4jRefreshInterval</param-name>
  59. <param-value>6000</param-value>
  60. </context-param>
  61. <listener>
  62. <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  63. </listener>
  64. <listener>
  65. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  66. </listener>
  67. <!-- 防止spring内存溢出监听器 -->
  68. <listener>
  69. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  70. </listener>
  71. <!-- springMVC核心配置 -->
  72. <servlet>
  73. <servlet-name>dispatcherServlet</servlet-name>
  74. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  75. <init-param>
  76. <param-name>contextConfigLocation</param-name>
  77. <!--spingMVC的配置路径 -->
  78. <param-value>classpath:springmvc/spring-mvc.xml</param-value>
  79. </init-param>
  80. <load-on-startup>1</load-on-startup>
  81. </servlet>
  82. <!-- 拦截设置 -->
  83. <servlet-mapping>
  84. <servlet-name>dispatcherServlet</servlet-name>
  85. <url-pattern>/</url-pattern>
  86. </servlet-mapping>
  87. <!-- 配置session超时时间,单位分钟 -->
  88. <session-config>
  89. <session-timeout>15</session-timeout>
  90. </session-config>
  91. <error-page>
  92. <error-code>404</error-code>
  93. <location>/WEB-INF/views/error/404.jsp</location>
  94. </error-page>
  95. <error-page>
  96. <error-code>401</error-code>
  97. <location>/WEB-INF/views/error/401.jsp</location>
  98. </error-page>
  99. </web-app>

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

5、登陆页面login.jsp

以下是默认登陆的界面

  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

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

  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><a href="${ctx}/logout.html">退出</a>
  19. <p>一、验证当前用户是否为"访客",即未认证(包含未记住)的用户</p>
  20. <shiro:guest>
  21. Hi there!  Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> 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 information</a>.
  30. </shiro:authenticated>
  31. <p>四、未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。</p>
  32. <shiro:notAuthenticated>
  33. Please <a 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. <a 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. <shiro:hasPermission name="delete">
  54. <p>当前用户拥有删除的权限!!!!!!!!!!!!!</p>
  55. </shiro:hasPermission>
  56. </body>
  57. </html>

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

7、controller层来看看

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

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

再来看看效果吧!

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

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

Shrio登陆验证实例详细解读(转)的更多相关文章

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

    最终效果如下: 工程整体的目录如下: Java代码如下: 配置文件如下: 页面资源如下: 好了,下面来简单说下过程吧! 准备工作: 先建表: [sql] view plain copy drop ta ...

  2. Shiro与基本web环境整合登陆验证实例

    1. 用maven导入Shiro依赖包 <dependency> <groupId>org.apache.shiro</groupId> <artifactI ...

  3. form表单使用(博客系统的登陆验证,注册)

    先从小的实例来看form的用法 登陆验证实例,来看form的常规用法 1. forms.py # 用于登陆验证验证 from django.core.validators import RegexVa ...

  4. 登陆验证系统实例-三种(cookie,session,auth)

    登陆验证 因为http协议是无状态协议,但是我们有时候需要这个状态,这个状态就是标识 前端提交from表单,后端获取对应输入值,与数据库对比,由此对象设置一个标识,该对象 在别的视图的时候,有此标识, ...

  5. MemCache超详细解读

    MemCache是什么 MemCache是一个自由.源码开放.高性能.分布式的分布式内存对象缓存系统,用于动态Web应用以减轻数据库的负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高 ...

  6. MemCache超详细解读 图

    http://www.cnblogs.com/xrq730/p/4948707.html   MemCache是什么 MemCache是一个自由.源码开放.高性能.分布式的分布式内存对象缓存系统,用于 ...

  7. Shrio授权验证详解

    所谓授权,就是控制你是否能访问某个资源,比如说,你可以方位page文件夹下的jsp页面,但是不可以访问page文件夹下的admin文件夹下的jsp页面. 在授权中,有三个核心元素:权限,角色,用户. ...

  8. MemCache详细解读

    MemCache是什么 MemCache是一个自由.源码开放.高性能.分布式的分布式内存对象缓存系统,用于动态Web应用以减轻数据库的负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高 ...

  9. 从零开始实现asp.net MVC4框架网站的用户登录以及权限验证模块 详细教程

    从零开始实现asp.net MVC4框架网站的用户登录以及权限验证模块 详细教程   用户登录与权限验证是网站不可缺少的一部分功能,asp.net MVC4框架内置了用于实现该功能的类库,只需要简单搭 ...

随机推荐

  1. 开发自己PHP MVC框架(一)

    本教程翻译自John Squibb 的Build a PHP MVC Framework in an Hour,但有所改动,原文地址:http://johnsquibb.com/tutorials 这 ...

  2. nodejs启动守护程序pm2

    nodejs启动守护程序pm2 by 伍雪颖 做了个应用,server放阿里云,只是server总会自己断,后来写了个心跳程序,就是检測应用线程是否还在,不在就再启动, 这种方法好笨重啊,后来发现no ...

  3. 我为什么要创建帮创业者找合伙人的缘创派(ycpai.com)?

    我为什么要创建帮助创业者找合伙人的缘创派(ycpai.com)? 在我发出第一条离开CSDN出来创业的微博后,感谢各位朋友的鼓励.很多朋友问我一些问题,我在这里一并回答,并简单阐述一下我的理念. 问: ...

  4. Datatables 在asp.net mvc

    Datatables 在asp.net mvc中的使用 前言 最近使用ABP(ASP.NET Boilerplate)做新项目,以前都是自己扩展一个HtmlHelper来完成同步/异步分页,但是有个地 ...

  5. VSTO学习笔记(五)批量编辑Excel 2010 x64

    原文:VSTO学习笔记(五)批量编辑Excel 2010 x64 近期因为工作的需要,经常要批量处理大量的Excel文件,如果纯手工一个个修改,非常的麻烦,于是写了这么一个帮助类,希望能对你有所帮助. ...

  6. Visual Prolog 的 Web 专家系统 (8)

    GENI核心 -- 推理引擎(2)流量控制 1.阐述fail."!"而回溯 与其他语言相比,,Prolog最大的特点.这是回溯机制. 回溯机制,还有的主要手段2个月,首先,通过使用 ...

  7. AC自动机---个人总结

    比较好的 AC自动机算法详解.. [转]http://www.cppblog.com/mythit/archive/2009/04/21/80633.html 个人总结:[图是盗用的..] ac自动机 ...

  8. cocos2dx 制作单机麻将(一)

    今天開始打算解说下cocos2dx下怎样制作国标麻将 前半部分先解说麻将的逻辑部分,由于都是代码,可能会比較枯燥无聊. 这部分讲完后,你也能够用其它游戏引擎来制作麻将 后半部分,就解说余下的cocos ...

  9. Android开发系列(二十二):AdapterViewFlipper的功能和使用方法

    AdapterViewFlipper继承了AdapterViewAnimator,它会显示一个View组件,能够通过showPrevious()和showNext()方法控制组件显示上一个.下一个组件 ...

  10. codeforces#256DIV2 D题Multiplication Table

    题目地址:http://codeforces.com/contest/448/problem/D 当时是依照找规律做的,规律倒是找出来了,可是非常麻烦非常麻烦. . 看到前几名的红名爷们3分钟就过了, ...