前端传给springboot的中文数据乱码的一种解决办法

前端传给springboot的中文数据乱码的一种解决办法

思路

我的思路是这样的,前端我用axios传数据给spring boot,使用get方式传中文,后端就会显示乱码,但如果使用post方式传数据,数据可以是字符串或者json,后端的类加@Restcontroller注解,对应的函数上,给参数加@RequestBody注解,要发送的中文最好url编码之后再发送(我发现,就算不编码,也会自动转为url编码格式发送),那么获取到的参数就不是乱码,是url编码之后的数据,之后在后端url解码就简单多了,这样,前端就可以无损的传中文到后端了。

代码

前端是这样的

var url = "foredoreview";
var params = {oid:vue.o.id,pid:vue.p.id,content:vue.content};  //content里面的是中文
axios.post(url,params).then(function(response){
							
		vue.showReviews = true;
		vue.load();
						
});

后端是这样的

...//类前要加@Restcontroller
@PostMapping("foredoreview")
public Object doreview(HttpSession session,@RequestBody JSONObject params) throws UnsupportedEncodingException{
		Order o = orderService.get((int)params.get("oid"));
		o.setStatus(OrderService.finish);
		orderService.update(o);

		Product p = productService.get((int)params.get("pid"));
		
		String content = (String)params.get("content");
		content = URLDecoder.decode(content,"UTF-8");//将中文url解码,可能会抛出UnsupportedEncodingException异常
...

JSONObject类是用于json解析的类,不是java本身自带的,它的依赖是

    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ezmorph</groupId>
        <artifactId>ezmorph</artifactId>
        <version>1.0.3</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>

URLDecoder是java.net里的类,自带的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值