Java web過濾器驗證登入(避免未經登入進入主頁)
阿新 • • 發佈:2018-12-11
1.首先寫一個許可權過濾filter類,實現Filter介面
1 import java.io.IOException; 2 3 import javax.servlet.Filter; 4 import javax.servlet.FilterChain; 5 import javax.servlet.FilterConfig; 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletRequest; 8 import javax.servlet.ServletResponse; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import javax.servlet.http.HttpSession; 12 13 public class LoginFilter implements Filter { 14 15 @Override 16 public void init(FilterConfig filterConfig) throws ServletException { 17 // TODO Auto-generated method stub 18 19 } 20 21 @Override 22 public void doFilter(ServletRequest request, ServletResponse response, 23 FilterChain chain) throws IOException, ServletException { 24 // 獲得在下面程式碼中要用的request,response,session物件 25 HttpServletRequest servletRequest = (HttpServletRequest) request; 26 HttpServletResponse servletResponse = (HttpServletResponse) response; 27 HttpSession session = servletRequest.getSession(); 28 29 // 獲得使用者請求的URI 30 String path = servletRequest.getRequestURI(); 31 //System.out.println(path); 32 33 // 從session裡取員工工號資訊 34 String empId = (String) session.getAttribute("empId"); 35 36 /*建立類Constants.java,裡面寫的是無需過濾的頁面 37 for (int i = 0; i < Constants.NoFilter_Pages.length; i++) { 38 39 if (path.indexOf(Constants.NoFilter_Pages[i]) > -1) { 40 chain.doFilter(servletRequest, servletResponse); 41 return; 42 } 43 }*/ 44 45 // 登陸頁面無需過濾 46 if(path.indexOf("/login.jsp") > -1) { 47 chain.doFilter(servletRequest, servletResponse); 48 return; 49 } 50 51 // 判斷如果沒有取到員工資訊,就跳轉到登陸頁面 52 if (empId == null || "".equals(empId)) { 53 // 跳轉到登陸頁面 54 servletResponse.sendRedirect("/JingXing_OA/login.jsp"); 55 } else { 56 // 已經登陸,繼續此次請求 57 chain.doFilter(request, response); 58 } 59 60 } 61 62 @Override 63 public void destroy() { 64 // TODO Auto-generated method stub 65 66 } 67 68 }
2.然後在web.xml裡配置需要登陸許可權驗證的JSP檔案: a.如果是某個具體的JSP檔案(如a.jsp)需要登陸驗證
<!-- 配置登陸過濾器 --> 2 <filter> 3 <filter-name>login</filter-name> 4 <filter-class>com.jingxing.oa.filter.LoginFilter</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>login</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
b.如果是某一個目錄(如a/目錄)整個目錄下的檔案都需要登陸驗證:
1 <!-- 配置登陸過濾器 --> 2 <filter> 3 <filter-name>login</filter-name> 4 <filter-class>com.jingxing.oa.filter.LoginFilter</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>login</filter-name> 9 <url-pattern>/a/*</url-pattern> 10 </filter-mapping>
--------------------- 本文來自 歡迎寫評語 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/dwn1209/article/details/51148674?utm_source=copy