返回> 网站首页
Tomcat请求过滤插件
yoours2022-09-04 18:40:51
简介一边听听音乐,一边写写文章。
一、参考代码结构
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();
}
}
}
}
}