I found a garbled problem on the Internet and found various versions. Now I found that all kinds of experiences are available...
Not to mention, the method of success is as follows:
1. Set page encoding everywhere. I have always set it to UTF-8. No exception is found;
2. For Ajax processing methods, see the source code.
$.ajax({type : "POST",contentType : "application/json",url : "ToHistoryServlet?handleFlag=add&sendPerson=" + sendPerson+ "¤tTime=" + currentTime() + "&message="+ encodeURIComponent(message) + "&recvPerson=" + recvPerson,dataType : 'json',success : function(result) {alert(result.d);}});
Note: A. Use the POST method;
B. Add encodeuricomponent before the Chinese character (encode the string as a URI component );
C. jquery is used in this example.
3. For details about how to handle servlet reception, see source code.
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String handleFlag = request.getParameter("handleFlag");Message msg = new Message();// handle chinese code dml@2012.8.29if (request.getParameter("message") != null) {msg.setMessage(new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8"));}msg.setRecvPerson(request.getParameter("recvPerson"));msg.setSendPerson(request.getParameter("sendPerson"));msg.setSendTime(request.getParameter("currentTime"));if (handleFlag.equals("add")) {HistoryHandle.addMessage(msg);} else if (handleFlag.equals("delete")) {HistoryHandle.deleteMessage(msg);}}
Note: A. Set the encoding method request. setcharacterencoding to UTF-8;
B. js default encoding is iso8859-1, so need to convert a bit
String xxxxx=new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8")
The above operation can solve the Ajax garbled problem.