Problem sending special characters to ajax mail request

I have to deal with the problem when sending special characters to ajax POST request, these special characters are not properly received by my servlet where the request is sent. Javascript Code:

myAjaxPostrequest=new GetXmlHttpObject(); var parameters1="content="+mainContent; myAjaxPostrequest.open("POST", "controller", true); myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); myAjaxPostrequest.send(parameters1); 

Servlet Code:

 String lsContentToSave = aoReq.getParameter("content"); System.out.println(lsContentToSave); 

aoReq - an HttpServletRequest object.

For example, if the special character is Β» , it prints »

I also tried jquery post and still ran into the same problem. Please let me know about this.

+4
source share
1 answer

You noted jquery-ajax , but the JS code in your question is not recognized as jQuery. Are you really using jQuery ? This is more like a w3schools poor textbook trick.

In any case, you need to consider the character encoding in two places. On the client side, when you form-encode the parameter, you should use encodeURIComponent() . This will apply percentage coding using UTF-8.

 var parameters = "content=" + encodeURIComponent(mainContent); // ... 

On the server side, until you get any parameter from the request body, you must set the request encoding in UTF-8 as follows:

 request.setCharacterEncoding("UTF-8"); // ... String content = request.getParameter("content"); // ... 

However, if you really use jQuery, you do not need to worry about using client side encodeURIComponent() . jQuery will handle all this for you if you use the $.post() function with a data object.

 $.post('controller', { 'content': mainContent}, function() { // Callback function here. }); 
+4
source

All Articles