日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

权限验证过滤器

發布時間:2025/3/20 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 权限验证过滤器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對session的驗證,如果沒有相對應的處理就拋出一個LoginException異常
本例添加URI與權限role角色檢查,這個配置文件存放在properties配置文件中

創建過濾器的實現類PriorityFilter.java,在該類中創建一個Properties對象,使它可以保存在流中或從流中加載,作用是保存所有的權限,并在初始化方法中獲取這個權限文件的位置和配置,在doFilter()中設置訪問的路徑與后綴的參數,組成新的URI

public class PriorityFilter implements Filter {private Properties pts=new Properties();@Overridepublic void destroy() {pts=null;}@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {HttpServletRequest request=(HttpServletRequest) req;//獲取訪問的路徑String requestURI=request.getRequestURI().replace(request.getContextPath()+"/","");//獲取action的參數String action=req.getParameter("action");action=action==null?"":action;//組成新的URIString uri=requestURI+"?action="+action;//在session中獲取用戶權限Stringrole=(String)request.getSession(true).getAttribute("role");role=role==null?"guest":role;boolean authentificated=false;//審核用戶是否有權限登錄訪問for(Object obj:pts.keySet()){String key=((String)obj);//使用正則表達式驗證,需要將?替換,通過通配符*處理if(uri.matches(key.replace("?", "\\?").replaceAll(".", "\\.").replace("*", ".*"))){//如果role角色匹配if(role.equals(pts.get(key))){authentificated=true;break;}}}if (!authentificated) {throw new RuntimeException(new LoginException("您無權訪問該頁面。請以合適的身份登錄后查看。"));}//下一個過濾器或者Servletchain.doFilter(req, res);}@Overridepublic void init(FilterConfig config) throws ServletException {//從初始化參數中獲取權限配置文件的位置String file=config.getInitParameter("file");String realPath=config.getServletContext().getRealPath(file);try{pts.load(new FileInputStream(realPath));}catch(Exception e){config.getServletContext().log("讀取權限文件錯誤",e);}}}

創建ExceptionFilter.java文件

public class ExceptionFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {try {chain.doFilter(request, response);} catch (Exception e) {Throwable rootCause = e;while (rootCause.getCause() != null) {rootCause = rootCause.getCause();}String message = rootCause.getMessage();message = message == null ? "òì3££o" + rootCause.getClass().getName(): message;request.setAttribute("message", message);request.setAttribute("e", e);if (rootCause instanceof LoginException) {request.getRequestDispatcher("/loginException.jsp").forward(request, response);}else {request.getRequestDispatcher("/error.jsp").forward(request,response);}}}public void init(FilterConfig arg0) throws ServletException {} }

創建LoginException.java文件

public class LoginException extends Exception {private static final long serialVersionUID = -3040955562136599570L;public LoginException(String msg) {super(msg);}}

loginException.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>權限驗證Filter</title> <style type="text/css"> body, td, div, input {font-size: 20px; } .error {padding: 3px; border: 1px solid #FF0000; background: url(images/error.gif) 8px 5px no-repeat lightblue; padding-left: 50px; } </style> </head> <body><div class="error" align="center"> ${ message } </div><form action="" method="post" ><table align="center"><tr><td>賬號</td><td><input type="text" name="account" /></td></tr><tr><td>密碼</td><td><input type="password" name="password" /></td></tr><tr><td>&nbsp;</td><td><input type="submit" value=" 登錄 " /></td></tr></table> </form></body> </html>

output.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${ pageContext.request.requestURI }</title> </head> <body><div align="center" style="font-size: x-large">用戶在瀏覽的是: ${ pageContext.request.requestURI }?${ pageContext.request.queryString }.</div> </body> </html>

error.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'error.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>異常錯誤頁面提示!!!</body> </html>

創建priority.properties配置文件,如果只有key-value屬性值,其中key鍵為訪問的地址,value為控制訪問的權限名稱

# Privilege Settingsadmin.do?action\=* = administrators login.do?action\=* = administrators method.do?action\=add = system method.do?action\=delete = system method.do?action\=save = system method.do?action\=view = guest method.do?action\=list = gue

web.xml文件配置

<welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><display-name>filter</display-name><servlet><servlet-name>dispatcherServlet</servlet-name><jsp-file>/output.jsp</jsp-file></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><filter><filter-name>exceptionFilter</filter-name><filter-class>com.cn.zj.Filter.ExceptionFilter</filter-class></filter><filter><filter-name>priorityFilter</filter-name><filter-class>com.cn.zj.Filter.PriorityFilter</filter-class><init-param><param-name>file</param-name><param-value>/WEB-INF/priority.properties</param-value></init-param></filter><filter-mapping><filter-name>exceptionFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter-mapping><filter-name>priorityFilter</filter-name><url-pattern>*.do</url-pattern></filter-mapping>

總結

以上是生活随笔為你收集整理的权限验证过滤器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。