(Spring + JSP + jQuery-AJAX + JSON)设置UTF-8问题的环境?
我正在用Spring 3.x
在java
中执行chat project
,这需要Multi-language support
.
I am doing a chat project
in java
with Spring 3.x
which needs Multi-language support
.
这就是我所做的.
我的JSP具有:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
我的web.xml
具有:
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在我的Tomcat server.xml
中具有:
<Connector (...) URIEncoding="UTF-8" />
我的Java environment
有:
JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8
在我的Spring-controller
中具有:
@RequestMapping(value="sendMessage.html",method=RequestMethod.POST)
public @ResponseBody String sendMessage(HttpSession session,@RequestParam String intxnId,@RequestParam String message, HttpServletRequest request,HttpServletResponse response){
String contentType= "text/html;charset=UTF-8";
response.setContentType(contentType);
//response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/json; charset=UTF-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("text/plain;charset=UTF-8");
System.out.println("Send Message UTF-8 ----------------- "+ message);
String json = null;
BasicChatProtocol protocol = CustomerManagement.protocol.put(intxnId, chatProtocol.getProtocol());
HashMap<String,String> result = send.send(message, intxnId, protocol);
result.put("name",(String) session.getAttribute("nickName"));
ObjectMapper map = new ObjectMapper();
if(result.size()!= 0){
try {
json = map.writeValueAsString(result);
result.clear();
result = null;
System.out.println("Send Message :::::::: : "+json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
我的jQuery-AJAX
将是:
function sendMessage(){
var intxnId = $("#hide").val();
var message = $("#message").val();
alert("send : \n intxnId : "+intxnId+"\nmessage : "+message);
$.ajax({
type: "POST",
cache: false,
url: contexPath + "/sendMessage.html",
async: true,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8",
dataType: 'html',
data: "intxnId=" + intxnId +"&message="+ encodeURIComponent(message),
success: function(response){
if(response != null && response !="" && response !="null"){
var txt = '{"data":['+response+']}';
var json = eval ("(" + txt + ")");
for(i =0;i<json.data.length;i++){
var data = json.data[i];
var name = data.name;
var message = data.message;
var time = data.time;
alert("Name : "+name+"\nMessage : "+message+"\ntime : "+time);
var createHTML = send(name,message,time);
$("#messageDisplayArea").append(createcreateHTML);
};
}
},
error: function(e){
alert('Error: ' + e);
},
});
}
但是当我发送本地语言消息அவர்களுக்கு
(泰米尔语)时,在alert box
和view page
中只有???????
.
But when I send the local language message அவர்களுக்கு
(Tamil language), I got only ???????
in the alert box
and the view page
.
但是我在控制台中找到了local language
(SysOut in controller
),并且所有Special Characters
都能正常工作.
But I got the local language
in the console(SysOut in controller
) and all Special Characters
works.
注意::我认为response from the controller
存在问题.因为当我将message
发送到controller
时,我在javascript alert
中得到了message as small boxes
.但是当response
出现时,我在alert box
中得到了?????
.
Note : I think I am having the problem with response from the controller
.Because when I send the message
to the controller
I got the message as small boxes
in javascript alert
. But when the response
came I am getting the ?????
in the alert box
.
我的控制台打印,
Send Message UTF-8 ----------------- அவர்களுக்கு
Mesge what I send :::: அவர்களுக்கு
Send Message :::::::: : {"message":"அவர்களுக்கு","time":"time","name":"Human"}
我不知道自己在想什么.
I don't know what I am missing.
注意::我没有使用任何data base
.
希望我们的堆栈用户会提供更好的解决方案.好的答案肯定会受到赞赏.
Hope our stack users will give a better solution. Good answers are definitely appreciated.
我已经使用此测试控制器尝试了您的javascript:
I have tried your javascript with this test controller:
@Controller
public class TestController {
@RequestMapping(value = "/test", method = POST, produces = "application/json; charset=utf-8")
public @ResponseBody
ResponseEntity<String> sendMessage(HttpSession session, @RequestParam String intxnId, @RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
}
它的工作原理像一种魅力,使用Chrome浏览器,我在警报弹出窗口中从响应中看到了UTF-8字符.
It works like a charm, and I see UTF-8 characters from the response in the alert popup, using chrome browser.
我的test.jsp:
My test.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Test</h1>
<input type="text" id="hide" />
<input type="text" id="message"/>
<button id="button">test</button>
<div id="messageDisplayArea"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$('#button').on('click', sendMessage);
function sendMessage() {
var intxnId = $("#hide").val();
var message = $("#message").val();
alert("send : \n intxnId : " + intxnId + "\nmessage : " + message);
$.ajax({
type: "POST",
cache: false,
url: "${pageContext.request.contextPath}/test",
async: true,
data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
success: function(response) {
if (response !== null && response !== "" && response !== "null") {
alert("Name : " + response.name + "\nMessage : " + response.message + "\ntime : " + response.time);
$("#messageDisplayArea").append(message);
}
},
error: function(e) {
alert('Error: ' + e);
},
});
}
</script>
</body>
</html>