代码
package cn.itcast.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;public class DemoFilter implements Filter { public DemoFilter() { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); System.out.println("这是自定义过滤器,设置字符编码集为UTF-8"); // pass the request along the filter chain chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("init: 初始化方法。。。"); }}
package com.demo.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 DemoServlet */@WebServlet("/DemoServlet")public class DemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("这是经过过滤之后的输出"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
将代码注释掉
过滤之前的情况
然后去掉注释
链接:https://pan.baidu.com/s/1rXs_3NdMVKteQKyLP6ao8g
提取码:5ko3 复制这段内容后打开百度网盘手机App,操作更方便哦