隐藏

SpringBoot中使用PrintWriter出现乱码-已亲自验证成功

发布:2022/3/17 16:12:35作者:管理员 来源:本站 浏览次数:1176

一、代码

@WebServlet(urlPatterns={"/abc"})
public class CharsetController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html,charset=utf-8");



        PrintWriter writer = resp.getWriter();

        writer.write("123abc一二三");
        writer.flush();
        writer.close();
    }


}

 

页面显示结果: 123abc涓€浜屼笁
二、解决

@WebServlet(urlPatterns={"/abc"})
public class CharsetController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html,charset=utf-8");
        //这里添加
        resp.setContentType("text/plain; charset=utf-8");


        PrintWriter writer = resp.getWriter();

        writer.write("123abc一二三");
        writer.flush();
        writer.close();
    }


}

   

页面显示: 123abc一二三
三、尝试其他的方法

applicaiton.properties中添加:

server.servlet.encoding.enabled=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true

 

结果:还是一样

使用全局过滤器:
package com.example.demo.config;   import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;   import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  @Order(-1)  @Component  public class CharsetFilter implements Filter {  @Override   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
   HttpServletRequest request=(HttpServletRequest)servletRequest;   HttpServletResponse response=(HttpServletResponse)servletResponse;   request.setCharacterEncoding("utf-8");   response.setCharacterEncoding("utf-8");   response.setContentType("text/html,charset=utf-8");  //添加   response.setContentType("text/plain; charset=utf-8");    filterChain.doFilter(request,response);    }
}