Filter(過濾器)與Listener(監聽器)詳解

wangyudong927發表於2022-02-19

11、Filter(重點)

Filter:過濾器,用來過濾網站的資料;

  • 處理中文亂碼
  • 登陸驗證...

Filter開發步驟:

  1. 導包

  2. 編寫過濾器

    1. 導包不要錯

    2. 實現Filter介面,重寫對應的方法即可

      public class CharacterEncodingFilter implements Filter {
      
          //初始化:web伺服器啟動,就已經初始化了,隨時等待過濾物件出現!
          public void init(FilterConfig filterConfig) throws ServletException {
              System.out.println("CharacterEncodingFilter初始化");
          }
      
          //Chain : 鏈
          /*
          1. 過濾器中的所有程式碼,在過濾特定請求的時候都會執行
          2. 必須要讓過濾器繼續通行
              filterChain.doFilter(servletRequest,servletResponse);
           */
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
              servletRequest.setCharacterEncoding("utf-8");
              servletResponse.setCharacterEncoding("utf-8");
              servletResponse.setContentType("text/html;charset=UTF-8");
      
              System.out.println("CharacterEncodingFilter執行前...");
              filterChain.doFilter(servletRequest,servletResponse); //讓我們的請求繼續走,如果不寫,程式到這裡就被攔截停止!
              System.out.println("CharacterEncodingFilter執行後...");
          }
      
          //銷燬:web伺服器關閉的時候,過濾器會銷燬
          public void destroy() {
              System.out.println("CharacterEncodingFilter銷燬");
          }
      }
      
    3. 在web.xml中配置 Filter

      <servlet>
          <servlet-name>ShowServlet</servlet-name>
          <servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>ShowServlet</servlet-name>
          <url-pattern>/servlet/show</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>ShowServlet</servlet-name>
          <url-pattern>/show</url-pattern>
      </servlet-mapping>
      
      <filter>
          <filter-name>CharacterEncodingFilter</filter-name>
          <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>CharacterEncodingFilter</filter-name>
          <!--只要是 /servlet的任何請求,都會經過這個過濾器-->
          <url-pattern>/servlet/*</url-pattern>
          <!--<url-pattern>/*</url-pattern>-->
      </filter-mapping>
      

12、監聽器

實現一個監聽器的介面; (有N中)

  1. 編寫一個監聽器

    實現監聽器的介面...

    //統計網站線上人數 : 統計session
    public class OnlineCountListener implements HttpSessionListener {
    
        //建立session監聽:看你的一舉一動
        //一旦建立一個session就會觸發一次這個事件!
        public void sessionCreated(HttpSessionEvent httpSessionEvent) {
            ServletContext context = httpSessionEvent.getSession().getServletContext();
    
            System.out.println(httpSessionEvent.getSession().getId());
    
            Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(1);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count+1);
            }
    
            context.setAttribute("OnlineCount",onlineCount);
        }
    
        //銷燬session監聽
        //一旦銷燬session就會觸發一次這個事件!
        public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
            ServletContext context = httpSessionEvent.getSession().getServletContext();
            Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(0);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
    
            context.setAttribute("OnlineCount",onlineCount);
        }
    
        /*
        Session銷燬:
        1. 手動銷燬 getSession.invalidate()
        2. 自動銷燬 在web.xml中設定session過期時間
         */
    }
    
  2. web.xml中註冊監聽器

    <!--註冊監聽器-->
    <listener>
        <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
    </listener>
    
  3. 看情況是否使用!

13、過濾器、監聽器常見應用

監聽器:GUI程式設計中經常使用;

public class TestPanel1 {
    public static void main(String[] args) {
        Frame frame = new Frame("中秋節快樂"); //新建一個窗體
        Panel panel = new Panel(null); //皮膚
        frame.setLayout(null); //設定窗體的佈局

        frame.setBounds(50,50,300,300);
        frame.setBackground(Color.blue); //設定背景顏色

        panel.setBounds(70,70,70,70); //設定背景顏色
        panel.setBackground(Color.GREEN);

        frame.add(panel);
        frame.setVisible(true);

        //監聽事件,監聽關閉事件,使用介面卡
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

實現:使用者登入之後才能進入主頁!使用者登出後就不能進入主頁了!

  1. 使用者登陸之後,向Session中放入使用者的資料

  2. 進入主頁的時候要判斷使用者是否已經登入;要求:在過濾器中實現!

    //ServletRequest    HttpServletRequest
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    
    if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
        httpServletResponse.sendRedirect("/error.jsp");
    }
    
    filterChain.doFilter(servletRequest, servletResponse);
    

專案全部程式碼:

public class Constant {
    public final static String USER_SESSION = "USER_SESSION";
}
=============================================================
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //獲取前端請求的引數
        String username = req.getParameter("username");

        if (username.equals("admin")){ //登陸成功
            req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else { //登入失敗
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
==========================================================================
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
        
        if (user_session!=null){
            req.getSession().removeAttribute(Constant.USER_SESSION);
            resp.sendRedirect("/Login.jsp");
        }else {
            resp.sendRedirect("/Login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
===============================================================================
public class SysFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        /*
        實現會員分級:
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP1){
                response.sendRedirect("/vip1/index.jsp");
            }
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP2){
                response.sendRedirect("/vip2/index.jsp");
            }
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP3){
                response.sendRedirect("/vip3/index.jsp");
            }
         */

        //ServletRequest    HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
            httpServletResponse.sendRedirect("/error.jsp");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>錯誤</h1>
<h3>沒有許可權,使用者名稱錯誤</h3>

<p><a href="/Login.jsp">返回登入頁面</a></p>

</body>
</html>
====================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>主頁</h1>

<p><a href="/servlet/logout">登出</a></p>

</body>
</html>
=======================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>登入</h1>

<form action="/servlet/login" method="post">
    使用者名稱:<input type="text" name="username"><br>
    <input type="submit">
</form>

</body>
</html>
========================================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.kuang.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.kuang.servlet.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/servlet/logout</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.kuang.servlet.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>
    
</web-app>

相關文章