Filter
简介:Filter过滤器是JavaWeb三大组件之一,是一个实现了javax.servlet.Filter 接口的类。过滤器对客户端和服务器端之间的请求与响应信息进行拦截过滤。当浏览器访问服务器中的目标资源时, 会被Filter拦截, 在Filter中进行预处理操作,然后再将请求转发给目标资源。服务器做出的响应也需要将响应发送给过滤器处理后, 才会发送给服务端。
Filter在通过init()方法完成初始化,在doFilter()方法中对请求响应进行拦截过滤,通过chain.doFilter()放行相应资源。当有多个Filter时按照其配置顺序加载。
使用场景:解决post请求乱码问题,控制浏览器缓存页面资源,控制权限,自动登录等。
实例:对post请求的中文乱码进行处理
package com.sl.filter;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 实现过滤器
*/
@WebFilter("/*")//拦截所有资源
public class MyFilter01 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("****MyFilter01初始化****");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("****MyFilter01开始处理****");
//基于HTTP
HttpServletRequest request2 = (HttpServletRequest)request;
HttpServletResponse response2 = (HttpServletResponse)response;
//处理post请求乱码
request2.setCharacterEncoding("UTF-8");
//放行资源
chain.doFilter(request2, response2);
System.out.println("****MyFilter01处理结束****");
}
@Override
public void destroy() {
System.out.println("****MyFilter01被销毁****");
}
}
package com.sl.servlet;
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;
/**
* Servlet implementation class MyServlet01
*/
@WebServlet("/MyServlet01")
public class MyServlet01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet01() {
System.out.println("****MyServlet01实例化****");
}
@Override
public void init() throws ServletException {
System.out.println("****MyServlet01初始化****");
}
@Override
public void destroy() {
System.out.println("****MyServlet01被销毁****");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("姓名:"+ request.getParameter("uname"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="MyServlet01" method="post">
姓名:<input type="text" name="uname">
<button>提交</button>
</form>
</body>
</html>
|