Search code examples
javascriptjavastruts-1

Struts 1.3 Ajax call Japanese character encoding issue


I am using Java 1.7 and struts 1.3 framework. I am working for Japanese client. Currently my requirement is to send Search key (containing Japanese string) to the Action class using JQuery Ajax call. But at the action side I found some Japanese character are corrupted.

My code:

var searchKey = $('#searchtxt').val(); 
// some Japanese string value for search.

 var data = {
   // other properties
    "searchKey": searchKey,
   // Other properties
};

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    success: function (resultData){//dostuff}
});

I am quite new to SO I don't know how to format.

I have tried many solution on SO but not work for me. Any help will be appreciated. Thank you for any help.


Solution

  • To solve this Japanese encoding problem, use URL Encoding mechanism and then send data through ajax call. And then at the Struts action side simply you need to decode it by using URL decoder mechanism. It will solve this problem. For the more clarity see the below code.

    At the Java script side while fetching data from the hidden field use URL encoding method:

     var searchKey = encodeURIComponent($('#searchtxt').val().trim());
     // It will encode the Japanese string before send from Ajax call. 
    

    At the Struts Action side use URLDecoder class to decode the string value:

    String searchKey=form.getSearchKey();
        if(!searchKey.isEmpty()) //Check for empty or null string
           {
             // Decode the string using URLDecoder class from java.net package
             form.setSearchKey(URLDecoder.decode(searchKey, "UTF-8"));
           }