编程语言
首页 > 编程语言> > [javaweb]过滤器处理乱码

[javaweb]过滤器处理乱码

作者:互联网

过滤器

有一些信息不应该被处理,要被过滤的。

1.导包

<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.2-b01</version>
</dependency>

2.继承过滤器的接口

package com.javaweb.controller;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author panglili
 * @create 2022-07-20-20:32
 */
public class FilterDemo1 implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       servletRequest.setCharacterEncoding("utf-8");
       servletResponse.setCharacterEncoding("utf-8");
       servletResponse.setContentType("text/html;charset=utf-8");
        System.out.println("****before:");
        //让请求继续执行,如果不写请求到这里就会停止
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("####after:");

    }

    public void destroy() {
        System.out.println("destory……");
    }
}

3.写一个没有处理编码的请求

package com.javaweb.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author panglili
 * @create 2022-07-20-8:26
 */
public class tets extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username="弄啥嘞~";
        context.setAttribute("username",username);
        resp.getWriter().write(username);
    }



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


}

此时还没有配置过滤器,看看网页效果

意料之中的乱码。

4.将过滤器注册到web配置

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>com.javaweb.controller.FilterDemo1</filter-class>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/filter</url-pattern>
</filter-mapping>

5.经过过滤器的处理

标签:javaweb,ServletException,void,乱码,过滤器,import,servlet,javax
来源: https://www.cnblogs.com/lumanmanqixiuyuanxi/p/16512704.html