Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

springboot controller中请求参数中文乱码

controller如下:

@Controller
@RequestMapping("/publish")
class PublishController {
    @RequestMapping
    @ResponseBody
    public String publish(@RequestBody String data) throws UnsupportedEncodingException {
        System.out.println("the data is "+data);
        System.out.println("the data2 is "+ new String(data.getBytes("UTF-8"), "GBK"));
        return "success";
    }
}

打印结果:

the data is {"classify":"???","title":"1"}
the data2 is {"classify":"软件","title":"1"}

也就是说请求的编码是UTF-8,但是spring用GBK解码成String了。

我设置了StringHttpMessageConverterUTF-8也不好使。

这个解码在哪里设置吗?为什么默认的解码是GBK?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

自己回答一下吧。搞了半天才搞出来。自己基本上将网上所有的搜索出来的乱码方式设置了一下,发现都不行。根本的原因其实不在spring,而在于java。

请求中参数通过网络传过来肯定是字节的形式,而字节形式构造成String是采用什么编码呢?是平台默认编码。见官方文档

public?String(byte[]?bytes)
Constructs a new String by decoding the specified array of bytes using the platform's defaultcharset.

也就是说,spring在 new String(bytes) 时其实在用 new String(bytes, defaultEncoding)

那么平台默认的编码是什么呢?这个可以通过System.getProperty("file.encoding")获得,很不幸,是GBK。

发现这个问题是因为用springboot的main方法启动就没有问题,而用maven插件的springboot:run启动就有问题。那么解决方法也显而易见,在maven插件中设置一下:

<configuration>
    <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
</configuration>

用main方法启动打印的平台默认编码是UTF-8。

那么为什么spring的main方法就会设置UTF-8呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...