返回> 网站首页 

Tomcat请求过滤插件

yoours2022-09-04 18:40:51 阅读 1638

简介一边听听音乐,一边写写文章。

一、参考代码结构

package com.berryz2007.soskp;

//----------------------------------------

// Tomcat 10 用以下的 import

//import jakarta.servlet.http.HttpServlet;

//import jakarta.servlet.http.HttpServletRequest;

//import jakarta.servlet.http.HttpServletResponse;

//----------------------------------------

// Tomcat 9 用以下的 import

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

//----------------------------------------

import javax.servlet.*;

import java.io.File;

import java.io.FileOutputStream;


public class RequestFilter implements Filter {

    @Override

    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override

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

        if(!(servletRequest instanceof HttpServletRequest)){

            return;

        }

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        将请求输出到日志

        writeInFile(request.getRequestURI());

        filterChain.doFilter(servletRequest, servletResponse);

    }


    @Override

    public void destroy() {

    }


    public void writeInFile(String str) {

        File f = new File("D:\\test_fi.txt");

        FileOutputStream fos = null;

        try {

            if (!f.exists())

                f.createNewFile();

            fos = new FileOutputStream(f, true);

            String content = str + "\r\n";

            fos.write(content.getBytes());

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}


二、使用maven搭建编译
    使用tomcat的lib目录下的servlet-api.jar编译提示找不到javax.servlet.http,直接在pom.xml中添加:
<dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

三、配置tomcat
将编译好的jar文件拷贝到tomcat的lib目录下,web修改conf下的web.xml文件:

<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>com.berryz2007.soskp.RequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
配置好后,启动tomcat即可。


微信小程序扫码登陆

文章评论

1638人参与,0条评论