过滤器 filter

使用过滤器解决乱码问题

servlet
public class test1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("你好,世界");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

给servlet配置两个访问地址

    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>servlet.test1</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/servlet/test</url-pattern>
    </servlet-mapping>

filter

实现filter

  1. 继承Filter接口(javax.servlet)
  2. 实现doFilter方法
public class Filter implements javax.servlet.Filter {

    //服务器启动时即执行init
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("##########################初始化Filter");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=UTF-8");

        System.out.println("¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥doFilter之前");

        //让请求继续执行,如果不写这句,程序到这里就被截停
        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥doFilter之后");
    }

    //服务器关闭时执行destroy
    public void destroy() {

        System.out.println("销毁Filter###########################################");
    }
}
    <filter>
        <filter-name>filterEncoding</filter-name>
        <filter-class>filter.Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filterEncoding</filter-name>
        <!--过滤/servlet下的一切请求-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
结果

通过过滤器(解决乱码)的请求能够正常显示
在这里插入图片描述
不通过过滤器的请求显示乱码
在这里插入图片描述

posted @ 2022-01-25 19:50  ︶ㄣ演戲ㄣ  阅读(5)  评论(0编辑  收藏  举报  来源