Apache Shiro教程(三)Web应用程序
1、配置web.xml
主要用于配置Shiro监听、过滤器及自定义servlet
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 5 version="2.5"> 6 7 <listener> 8 <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class> 9 </listener> 10 11 <filter> 12 <filter-name>ShiroFilter</filter-name> 13 <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class> 14 </filter> 16 <filter-mapping> 17 <filter-name>ShiroFilter</filter-name> 18 <url-pattern>/*</url-pattern> 19 <dispatcher>ERROR</dispatcher> 20 <dispatcher>FORWARD</dispatcher> 21 <dispatcher>INCLUDE</dispatcher> 22 <dispatcher>REQUEST</dispatcher> 23 </filter-mapping> 24 25 <servlet> 26 <servlet-name>AppController</servlet-name> 27 <servlet-class>com.cnblogs.javalouvre.controller.AppController</servlet-class> 28 </servlet> 30 <servlet-mapping> 31 <servlet-name>AppController</servlet-name> 32 <url-pattern>/AppController</url-pattern> 33 </servlet-mapping> 34 35 <welcome-file-list> 36 <welcome-file>index.html</welcome-file> 37 <welcome-file>index.htm</welcome-file> 38 <welcome-file>index.jsp</welcome-file> 39 </welcome-file-list> 40 41 </web-app>
2、shiro.ini
shiro.ini 配置文件在上一个教程的基础上,增加 [urls] 部分,用户设置过滤器
1 # =================================================================================== 2 # Shiro INI configuration 3 # =================================================================================== 4 [main] 5 hashedCredentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher 6 hashedCredentialsMatcher.hashAlgorithmName = SHA-512 7 hashedCredentialsMatcher.hashIterations = 1024 8 hashedCredentialsMatcher.storedCredentialsHexEncoded = false 9 saltAwareIniRealm = com.cnblogs.javalouvre.shiro.realm.text.SaltAwareIniRealm 10 saltAwareIniRealm.resourcePath = classpath:shiro.ini 11 saltAwareIniRealm.credentialsMatcher = $hashedCredentialsMatcher 12 securityManager.realm = $saltAwareIniRealm 13 ehCacheManager = org.apache.shiro.cache.ehcache.EhCacheManager 14 ehCacheManager.cacheManagerConfigFile = classpath:ehcache.xml 15 securityManager.cacheManager = $ehCacheManager 16 authc.loginUrl = /login.jsp 17 18 [users] 19 system = E18H4biesus/SiiAyGb/sLDHpRACpwofpmKAgYojqxG8w1mX9aFGu51/O+ha02fpr4zoQXfyE/W919KWv7RwLA==, admin 20 scott = rzN+XZiPCHa+8O9c7jCnEzCE0BOgzitMU2x1aG6eg5f0wpnZcY9HaxyraO9NqUklI5y2bu1xrtgmJRrDe34xrg==, guest 21 22 [roles] 23 admin = * 24 guest = user:create, user:retrieve, user:update, user:delete 25 26 [urls] 27 /index.jsp = anon 28 /modules/* = authc 29 /logout = logout
3、登录首页
这里需要关注 shiro 的几个自定义标签
1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 <%@ include file="./common/header.ini"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 </head> 8 <body> 9 10 <h2>Please Log in</h2> 11 12 <shiro:guest> 13 <table border="1"> 14 <thead> 15 <tr> 16 <th>帐号</th> 17 <th>密码</th> 18 </tr> 19 </thead> 20 <tbody> 21 <tr> 22 <td>system</td> 23 <td>system</td> 24 </tr> 25 <tr> 26 <td>scott</td> 27 <td>tiger</td> 28 </tr> 29 </tbody> 30 </table> 31 <br/><br/> 32 <form name="loginform" action="${pageContext.request.contextPath}/AppController" method="post"> 33 <table align="left" border="0" cellspacing="0" cellpadding="3"> 34 <tr> 35 <td>帐号:</td> 36 <td><input type="text" id="username" name="username" value="${username}" maxlength="30"></td> 37 </tr> 38 <tr> 39 <td>密码:</td> 40 <td><input type="password" id="password" name="password" maxlength="30"></td> 41 </tr> 42 <tr> 43 <td colspan="2" align="left"><input type="checkbox" name="rememberMe" <c:if test="${not empty rememberMe}">checked</c:if>><font size="2">记住我</font></td> 44 </tr> 45 <tr> 46 <td colspan="2" align="right"><input type="submit" name="submit" value="登录"></td> 47 </tr> 48 <c:if test="${not empty error}"> 49 <tr> 50 <td colspan="2" align="right"><span style="color: #FF0000;">${error}</span></td> 51 </tr> 52 </c:if> 53 </table> 54 </form> 55 </shiro:guest> 56 </body> 57 </html>
4、登录验证servlet
1 package com.cnblogs.javalouvre.controller; 2 3 import java.io.IOException; 4 5 import javax.servlet.RequestDispatcher; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.commons.lang.StringUtils; 12 import org.apache.shiro.SecurityUtils; 13 import org.apache.shiro.authc.AuthenticationException; 14 import org.apache.shiro.authc.IncorrectCredentialsException; 15 import org.apache.shiro.authc.LockedAccountException; 16 import org.apache.shiro.authc.UnknownAccountException; 17 import org.apache.shiro.authc.UsernamePasswordToken; 18 import org.apache.shiro.subject.Subject; 19 import org.apache.shiro.web.util.WebUtils; 20 import org.slf4j.Logger; 21 import org.slf4j.LoggerFactory; 22 23 public class AppController extends HttpServlet { 24 25 private static final long serialVersionUID = -7325364540551054724L; 26 private static final Logger logger = LoggerFactory.getLogger(AppController.class); 27 28 @Override 29 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 30 this.doPost(req, resp); 31 } 32 33 @Override 34 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 35 String path = "/modules/main.jsp"; 36 37 Subject subject = SecurityUtils.getSubject(); 38 if (!subject.isAuthenticated()) { 39 String message = null; 40 String username = WebUtils.getCleanParam(req, "username"); 41 String password = WebUtils.getCleanParam(req, "password"); 42 String rememberMe = WebUtils.getCleanParam(req, "rememberMe"); 43 44 UsernamePasswordToken token = new UsernamePasswordToken(username, password); 45 if (StringUtils.isNotBlank(rememberMe)) { 46 token.setRememberMe(true); 47 } 48 try { 49 subject.login(token); 50 } catch (UnknownAccountException uae) { 51 logger.info("There is no user with username of " + token.getPrincipal()); 52 message = "用户 " + token.getPrincipal() + " 不存在!"; 53 } catch (IncorrectCredentialsException ice) { 54 logger.info("Password for account " + token.getPrincipal() + " was incorrect!"); 55 message = "用户 " + token.getPrincipal() + " 密码输入有误!"; 56 } catch (LockedAccountException lae) { 57 logger.info("The account for username " + token.getPrincipal() + " is locked. Please contact your administrator to unlock it."); 58 message = "帐号 " + token.getPrincipal() + " 已锁,请联系管理员解锁!"; 59 } catch (AuthenticationException e) { 60 logger.info(e.getMessage()); 61 message = e.getMessage(); 62 } 63 token.clear(); 64 if (StringUtils.isNotBlank(message)) { 65 req.setAttribute("username", username); 66 req.setAttribute("rememberMe", rememberMe); 67 req.setAttribute("error", message); 68 69 path = "/login.jsp"; 70 } 71 } 72 73 RequestDispatcher dispatcher = req.getRequestDispatcher(path); 74 dispatcher.forward(req, resp); 75 } 76 77 }
5、登录成功页面
1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 <%@ include file="/common/header.ini"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title></title> 8 </head> 9 <body> 10 <shiro:user> 11 User: 【<shiro:principal />】<br /> 12 Role: 【<shiro:hasRole name="admin">admin</shiro:hasRole><shiro:hasRole name="guest">guest</shiro:hasRole>】<br /> 13 Permission: 【<shiro:hasPermission name="*">*|</shiro:hasPermission> 14 <shiro:hasPermission name="user:create">user:create</shiro:hasPermission>】<br /> 15 <shiro:hasPermission name="user:retrieve">user:retrieve</shiro:hasPermission>】<br /> 16 <shiro:hasPermission name="user:update">user:update</shiro:hasPermission>】<br /> 17 <a href="${pageContext.request.contextPath}/logout">退出</a> 18 </shiro:user> 19 </body> 20 </html>
-----------------------------------------------------------------------------------------------------------
薔薇猛虎皆成個性,陽光雨露俱是天恩!
薔薇猛虎皆成個性,陽光雨露俱是天恩!
浙公网安备 33010602011771号