spring Boot 中文返回给浏览器乱码 解析成问号??fastJsonjackJson

    xiaoxiao2021-03-25  72

    心路历程:

    在Controller中return 对象的时候,对象中的属性值中文部分在浏览器中 显示为问号??

    @ResponseBody @RequestMapping(value = "/test") public String view(@PathVariable Integer id) { //*** return jsonVO.toString(); } 然后结果是这样的:??

    尝试排查原因:

    中文乱码常有以下三种:

    1.request、response里面的这个编码设置 2.Tomcat 编码设置 3.数据库编码设置

    逐一排查:首先我直接return “中文”;结果还是乱码。数据库编码   排除;

    然后我写了个过滤器:

    @WebFilter(filterName = "myFilter", urlPatterns = "/*") public class MyFilter implements Filter { @Override public void destroy() { System.out.println("过滤器销毁"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("执行过滤操作"); response.setCharacterEncoding("UTF-8"); System.out.println(response.getCharacterEncoding()); request.setCharacterEncoding("UTF-8"); System.out.println(request.getCharacterEncoding()); chain.doFilter(request, response); } @Override public void init(FilterConfig config) throws ServletException { System.out.println("过滤器初始化");失败,返回依然是乱码;

    接着尝试:

    return new String("中文".getBytes(), "UTF-8");  

    失败,返回依然是乱码;

    接着尝试:

     produces = { "application/json;charset=UTF-8" }

     @RequestMapping(value = "/test", produces = { "application/json;charset=UTF-8" })

    成功是成功了,可是这样感觉很奇怪,总不能每一个RequestMapping 都这样注解吧。

    然后我就发现我封装的jsonVO中使用的是fastjson 会不会是这个问题呢?

    springboot 引入的json是 Jackjson,撞墙的想法都有了。

    果断处理:Application extends WebMvcConfigurerAdapter

    重写方法。

    @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastConverter); } 可以了。

    如果觉得继承这个WebMvcConfigurerAdapter类影响你继承其他类,也可以写个@bean 放在Application  中

    retunr    HttpMessageConverter 类型就好;

    总结:

    1.添加  produces = { "application/json;charset=UTF-8" }

    2.重写configureMessageConverters方法;

    3.@bean  HttpMessageConverter ;

    转载请注明原文地址: https://ju.6miu.com/read-26380.html

    最新回复(0)