解决中文乱码

解决中文乱码

解决后端响应前端时的中文乱码

package org.example.filter;

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

public class CharacterEncodingFilter implements Filter {
    /**
     * 初始化:web服务器启动时就初始化了,等待过滤对象的出现
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化了");
    }

    @Override
    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("CharacterEncodingFilter执行前");
        //让我们的请求继续走,如果不写,程序到这里就被拦截停止了
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("CharacterEncodingFilter执行后");
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁了");
    }
}

web.xml配置

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.example.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--只要是 /servlet的任何请求,都会经过这个过滤器-->
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>
posted @ 2021-10-13 08:33  (x²+y²-1)³=x²y³  阅读(161)  评论(0编辑  收藏  举报