📜  Java Servlet 过滤器示例

📅  最后修改于: 2022-05-13 01:54:45.551000             🧑  作者: Mango

Java Servlet 过滤器示例

过滤器是在服务器上对请求进行预处理和后处理时调用的对象,即在执行用于过滤请求的 servlet 之前和之后。 Filter API(或接口)包括一些帮助我们过滤请求的方法。要理解Filters的概念,首先应该对Servlet的概念有一个了解。

我们为什么要使用过滤器?

验证来自客户端的数据,因为通过服务器,数据将存储在数据库中。因此,只有有效数据才能进入数据库。我们不能在客户端做这个验证(或添加过滤器)吗?我们可以在客户端添加过滤器。但是如果在客户端禁用了 javascript,则不会检查请求(或数据)。有人可能会故意这样做。所以为了避免这种情况,我们在服务器端添加过滤器。

使用过滤器的优点

  • 资源请求的认证和授权。 (检查用户是否有效,然后转发其请求。)
  • 在将请求正文或标头发送到 servlet 之前对其进行格式化。 (格式化未格式化的数据)
  • 压缩发送给客户端的响应数据。 (例如,加密)
  • 通过添加一些 cookie、标头信息等来更改响应。
  • 输入验证。 (最小鬼)

如何使用 API 过滤器实现过滤器?

  • 在实现过滤器 API(或接口)时请记住以下内容 -
    • 三种方法——init()、doFilter()、destroy()。必须重写这些方法。它们是过滤器的生命周期方法。
    • doFilter 将在预处理 + 后处理中执行。
    • doFilter() 方法接受三个参数——ServletRequest、ServletResponse、FilterChain。借助FilterChain,我们可以在认证成功后转发请求。

创建用户定义的过滤器类

创建一个实现Filter 接口并覆盖其所有方法的类,即init()、doFilter()、destroy()。如果我们不重写这些方法,那么我们的类也将成为一个抽象类。在“chain.doFilter()”之前编写的代码将在 servlet 之前运行(预处理),在“chain.doFilter()”之后编写的代码将在 servlet 之后运行(后处理)。

配置过滤器

  • 在 web.xml 中配置这个类(用户定义的过滤器)。
  • 在 web.xml 中映射此类(用户定义的过滤器)以指定何时执行。

例子

为了运行以下程序,我使用了 Eclipse IDE 和 Apache Tomcat Server v9.0

1) 创建 index.html

HTML


  
      Page Title
  
  
    

Welcome To GFG

    
             
  


Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
// Servlet implementation class GFGServlet
@WebServlet("/GFGServlet")
public class GFGServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    // @see HttpServlet#HttpServlet()
    public GFGServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }
  
    // @see HttpServlet#doGet(HttpServletRequest request,
    // HttpServletResponse response)
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        out.println("

Welcome to the Servlet.");         // This will print output on console         System.out.println("GFGServlet is running");     }        // @see HttpServlet#doPost(HttpServletRequest request,     // HttpServletResponse response)     protected void doPost(HttpServletRequest request,                           HttpServletResponse response)         throws ServletException, IOException     {         // TODO Auto-generated method stub         doGet(request, response);     } }



Java
import java.io.IOException;
import java.io.PrintWriter;
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 GFGFilter implements Filter {
  
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
    }
  
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
  
        PrintWriter out = response.getWriter();
  
        // This will print output on console
        System.out.println(
            "Before filter - Preprocessing before servlet");
  
        // some authentication if required
        chain.doFilter(request, response);
        
        // This will print output on console
        System.out.println(
            "After servlet - Following code will execute after running the servlet - PostProcessing"); 
    }
  
    public void destroy() {}
}


XML


  GFGFilter
  
      index.html 
      index.htm
      index.jsp
      default.html
      default.htm
      default.jsp
  
    
  
      filter1
      com.app.GFGFilter
  
    
  
      filter1
      /GFGServlet
  
    


2) 创建一个servlet GFGServlet。Java

Java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
// Servlet implementation class GFGServlet
@WebServlet("/GFGServlet")
public class GFGServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    // @see HttpServlet#HttpServlet()
    public GFGServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }
  
    // @see HttpServlet#doGet(HttpServletRequest request,
    // HttpServletResponse response)
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        out.println("

Welcome to the Servlet.");         // This will print output on console         System.out.println("GFGServlet is running");     }        // @see HttpServlet#doPost(HttpServletRequest request,     // HttpServletResponse response)     protected void doPost(HttpServletRequest request,                           HttpServletResponse response)         throws ServletException, IOException     {         // TODO Auto-generated method stub         doGet(request, response);     } }

3)创建一个类GFGFilter。 Java并实现Filter接口

Java

import java.io.IOException;
import java.io.PrintWriter;
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 GFGFilter implements Filter {
  
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
    }
  
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
  
        PrintWriter out = response.getWriter();
  
        // This will print output on console
        System.out.println(
            "Before filter - Preprocessing before servlet");
  
        // some authentication if required
        chain.doFilter(request, response);
        
        // This will print output on console
        System.out.println(
            "After servlet - Following code will execute after running the servlet - PostProcessing"); 
    }
  
    public void destroy() {}
}

4)web.xml中filter的配置和映射

XML



  GFGFilter
  
      index.html 
      index.htm
      index.jsp
      default.html
      default.htm
      default.jsp
  
    
  
      filter1
      com.app.GFGFilter
  
    
  
      filter1
      /GFGServlet