【过滤器解决中文乱码问题实例】
【工程截图】
【web.xml】
FilterDemo01 index.jsp FilterTest01 com.Higgin.web.filter.FilterTest01 FilterTest01 /*
【servletTest01.java】
package com.Higgin.web.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 ServletTest01 */@WebServlet("/ServletTest01")public class ServletTest01 extends HttpServlet { private static final long serialVersionUID = 1L; public ServletTest01() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("中国 加油!China Come on!"); //将"中国 加油!China Come on!"显示在客户端界面上 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }}
【情况一:未添加中文乱码过滤】
【FilterTest01.java】
package com.Higgin.web.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 FilterTest01 implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("I'm Filter!!!!"); //直接放行 chain.doFilter(request, response);//让目标资源执行,即:放行 } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void destroy() { }}
【运行结果】
浏览器端
控制台
【情况二:在Filter的都doFilter()方法中添加中文乱码过滤处理】
【FilterTest01.java】
package com.Higgin.web.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 FilterTest01 implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("I'm Filter!!!!"); //对request和response进行一些预处理 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;character=UTF-8"); chain.doFilter(request, response);//让目标资源执行,即:放行 } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void destroy() { }}
【运行结果】
浏览器端
控制台
【三种典型应用概述】
1.可以在Filter中根据条件决定是否调用chain.doFilter(request,response)方法,即是否放行让目标资源执行。
2.在目标资源执行之前,可以对request/response做预处理,再让目标资源执行。(如:为request和reponse设置编码为utf-8,以解决中文乱码问题)
3.让目标资源执行之后,可以捕获目标资源的执行结果,从而实现一些特殊的功能。