• filter


    filter 基本上和servlet一样。

    package com.atguigu.javaweb;
    
    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;
    
    public class HelloFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            System.out.println("init..");
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            System.out.println("1. Before HelloFilter's chain.doFilter ..."); //1
            
            //放行
            chain.doFilter(request, response);
            
            System.out.println("2. After HelloFilter's chain.doFilter ..."); //2
        }
    
        @Override
        public void destroy() {
            System.out.println("destroy...");
        }
    
    }

    在web.xml中进行配置:

    <filter>
        <filter-name>helloFilter</filter-name>
        <filter-class>com.atguigu.javaweb.HelloFilter</filter-class>
        <init-param>
          <param-name>name</param-name>
          <param-value>root</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>helloFilter</filter-name>
        <url-pattern>/test.jsp</url-pattern>
      </filter-mapping>

    filter的一些基本应用:

      1):浏览器页面缓存

      

    package cache;
    
    
    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;
    
    /**
     * 自定义的 HttpFilter, 实现自 Filter 接口
     *
     */
    public abstract class HttpFilter implements Filter {
    
        /**
         * 用于保存 FilterConfig 对象. 
         */
        private FilterConfig filterConfig;
        
        /**
         * 不建议子类直接覆盖. 若直接覆盖, 将可能会导致 filterConfig 成员变量初始化失败
         */
        public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
            init();
        }
    
        /**
         * 供子类继承的初始化方法. 可以通过 getFilterConfig() 获取 FilterConfig 对象. 
         */
        protected void init() {}
    
        /**
         * 直接返回 init(ServletConfig) 的 FilterConfig 对象
         */
        public FilterConfig getFilterConfig() {
            return filterConfig;
        }
        
        /**
         * 原生的 doFilter 方法, 在方法内部把 ServletRequest 和 ServletResponse 
         * 转为了 HttpServletRequest 和 HttpServletResponse, 并调用了 
         * doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
         * 
         * 若编写 Filter 的过滤方法不建议直接继承该方法. 而建议继承
         * doFilter(HttpServletRequest request, HttpServletResponse response, 
         *        FilterChain filterChain) 方法
         */
        
        public void doFilter(ServletRequest req, ServletResponse resp,
                FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            
            doFilter(request, response, chain);
        }
        
        /**
         * 抽象方法, 为 Http 请求定制. 必须实现的方法. 
         * @param request
         * @param response
         * @param filterChain
         * @throws IOException
         * @throws ServletException
         */
        public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, 
                FilterChain filterChain) throws IOException, ServletException;
    
        /**
         * 空的 destroy 方法。 
         */
    
        public void destroy() {}
    
    }
    package cache;
    
    import java.io.IOException;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class NoCacheFilter extends HttpFilter{
    
        @Override
        public void doFilter(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            response.setDateHeader("Expires", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            filterChain.doFilter(request, response);
                
        }
       }
    <!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>Insert title here</title>
    </head>
    <body>    
        <a href="b.html">TO BBB PAGE</a>
        <br><br>
        <img alt="" src="Hydrangeas.jpg">
    </body>
    </html>
    <!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>Insert title here</title>
    </head>
    <body>    
        <a href="a.html">TO AAA PAGE</a>
        <br><br>
    </body>
    </html>

    配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     <filter>
        <display-name>NoCacheFilter</display-name>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class>cache.NoCacheFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
        <url-pattern>/cache/*</url-pattern>
      </filter-mapping>
    </web-app>

    2):编码过滤器

      要不每次遇到中文编码的时候都会加上

      <%
          request.setCharacterEncoding("UTF-8");
       %>

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>My JSP 'encodingA.jsp' starting page</title>
      </head>
      <body>
          <form action="encodingB.jsp" method="post">
          name:<input type="text" name="name"/>
          <input type="submit" value="Submit"/>
          </form>
      </body>
    </html>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>My JSP 'encodingA.jsp' starting page</title>
      </head>
      <body>
          Hello: ${param.name }
      </body>
    </html>
    package com.encoding;
    
    import java.io.IOException;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cache.HttpFilter;
    
    public class EncodingFilter extends HttpFilter{
        private String encoding;
        @Override
        protected void init() {
            encoding=getFilterConfig().getServletContext().getInitParameter("encoding");
        }
        @Override
        public void doFilter(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            request.setCharacterEncoding(encoding);
            filterChain.doFilter(request, response);
        }
    
    }

    配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <context-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </context-param>
      <filter>
          <display-name>EncodingFilter</display-name>
          <filter-name>EncodingFilter</filter-name>
          <filter-class>com.encoding.EncodingFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>EncodingFilter</filter-name>
          <url-pattern>/encoding/*</url-pattern>
      </filter-mapping>
      
    </web-app>
  • 相关阅读:
    Python3安装turtle提示错误:Command "python setup.py egg_info" failed with error code 1
    慕学生鲜xadmin登录不成功解决办法
    mysql删除后ID不连续解决办法
    Mac 安装gevent
    ubuntu 下 docker的简单使用
    python 字典的一些简单操作
    列表推导式
    Serializer字段和选项
    添加包解决一些导包问题
    css 文本换行,文本空白符处理相关 属性:white-space word-wrap word-break
  • 原文地址:https://www.cnblogs.com/bulrush/p/7057600.html
Copyright © 2020-2023  润新知