过滤器的功能:过滤用户请求
Filter的创建: 第一步:创建一个类,实现Filter接口 第二步:调用他的init方法(初始化变量用的 服务器加载的时候就加载了),调用他的doFilter方法(里面的内容是你的Filter类要实现的功能),调用他的destroy方法(销毁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;public class CharsetEncodeFilter implements Filter { public void destroy() { System.out.println("CharsetEncodeFilter.destroy()"); }public void doFilter(ServletRequest Request, ServletResponse Response, FilterChain chain) throws IOException, ServletException { Response.setContentType("text/html; charset=utf-8");//作用是指定对服务器响应进行重新编码的编码。 Request.setCharacterEncoding("utf-8");//作用是设置对客户端请求进行重新编码的编码 chain.doFilter(Request, Response); }public void init(FilterConfig arg0) throws ServletException { System.out.println("CharsetEncodeFilter.init()"); }}
第三步:在xml文件中配置它的Filter类
CharsetEncodeFilter com.servlet.CharsetEncodeFilter CharsetEncodeFilter /*
第四步 :测试你的Filter功能是否正常
测试的jsp内容:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>Insert title here
测试的java代码:(浏览器默认的编码格式是iso—8859-1,与java输出的编码格式不匹配,所以会造成乱码,但是上面我们进行了Filter编码所以,如果没有出现乱码,就表示我们的Filter应用成功)
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;@WebServlet("/login")public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest Request, HttpServletResponse Response) throws ServletException, IOException { String name =Request.getParameter("name"); String password=Request.getParameter("password"); PrintWriter writer = Response.getWriter(); writer.write(name+password); }}