我有一个接受 POST/PUT 的 REST Web 服务,REST 调用正文中发送的资源同时包含法语和阿拉伯字符,但是当我发送包含一些阿拉伯字符的资源时,我会存储问号相反,在数据库中,如下所示: ??????
.
当我在数据库中手动输入阿拉伯字符时,它的存储没有任何问题,这只在我使用 POST 或 PUT 时发生,另一方面,GET 方法有效并且它获取阿拉伯字符。
这是请求 header 来源:
PUT /candidature/candidats HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 480
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/app/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
正如您在 Content-Type 中看到的那样,我有 charset=UTF-8
,因此在这种情况下应该可以工作。
这是我在 PUT/POST 方法中发送的资源示例:
{"username":"ichigo","nom":"Kurusaki","prenom":"Ichigo","nomarab":"كوروساكي","prenomarab":"إيتشيغو","genre":"M"}
在这种情况下,在 POST/PUT 后,GET 方法将获取阿拉伯字符作为问号:
{"codeUser":null,"username":"Asus","nom":"sdf","prenom":"Mbarek","nomarab":"????????","prenomarab":"???????","genre":"M"}
但是当我手动将它们输入数据库然后调用 GET 方法时,这就是我得到的结果:
{"codeUser":null,"username":"ichigo","nom":"Kurusaki","prenom":"Ichigo","nomarab":"كوروساكي","prenomarab":"إيتشيغو","genre":"M"}
所以这个问题只发生在 POST/PUT 方法中。
我在客户端使用 AngularJS,在服务器端使用 Spring boot。
那么为什么我会出现这种行为呢?我该如何解决它?
编辑:
在服务器端,我打印了阿拉伯值,然后使用 Spring boot 数据保存它们,如下所示:
System.out.print("arabicName : " + candidat.getNomarab());
在控制台中我得到了这个:
arabicName : كوروساكي
因此,当我调用 Sring Boot Data JPA 的 saveAndFlush
方法时,就会发生这种情况。
最佳答案
正如 @M.Deinum 提到的,这是一个连接配置错误,因此我将连接配置为使用 UTF-8,如下所示:
spring.datasource.url=jdbc:mysql://localhost:3306/db_myfme?useUnicode=yes&characterEncoding=UTF-8&characterSetResults=UTF-8
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true
server.tomcat.uri-encoding=UTF-8
# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
关于spring - 使用 Rest 和 spring boot 将阿拉伯字符保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909927/