Filter--對目錄實現URL級別的角色認證---學習筆記
阿新 • • 發佈:2018-04-19
Filter--對目錄實現URL級別的角login.html登陸
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/day19/welcome.jsp" method="post"> <table border="1" align="center"> <caption><br>用戶登錄</caption> <tr> <th>用戶名</th> <td><input type="text" name="username"/></td> </tr> <tr> <th>密碼</th> <td><input type="password" name="password"/></td> </tr> <tr> <th>角色</th> <td> <select name="role"> <option value="普通用戶">普通用戶</option> <option value="管理員">管理員</option> </select> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html>
fiter處理
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //對敏感目錄進行認證[課堂練習1] public class FilterDemo7 implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; //設置請求體編碼方式 request.setCharacterEncoding("UTF-8"); //取得用戶請求參數 String username = request.getParameter("username"); String password = request.getParameter("password"); String role = request.getParameter("role"); //判段 if(username!=null && password!=null && role!=null && username.trim().length()>0 && password.trim().length()>0 && role.trim().length()>0){ if("普通用戶".equals(role)){ request.setAttribute("message","歡迎普通用戶<font color=‘blue‘>"+username+"</font>登錄"); request.setAttribute("flag","user"); }else if("管理員".equals(role)){ request.setAttribute("message","歡迎管理員<font color=‘red‘>"+username+"</font>登錄"); request.setAttribute("flag","admin"); } chain.doFilter(request,response); } } public void destroy() { } }
結果顯示
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> ${message}<br/> <c:choose> <c:when test="${requestScope.flag==‘admin‘}"> <a href="#">下載</a> </c:when> <c:otherwise> 下載 </c:otherwise> </c:choose> </body> </html>
web.xml
<filter>
<filter-name>FilterDemo7</filter-name>
<filter-class>cn.itcast.web.filter.FilterDemo7</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo7</filter-name>
<url-pattern>/welcome.jsp</url-pattern>
</filter-mapping>
Filter--對目錄實現URL級別的角色認證---學習筆記