Search code examples
javaajaxjspspring-mvccyrillic

Sending Cyrillic string from jsp to java class trough ajax with correct encoding


I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.

The fields in the jsp page:

<div class="span1">
  <form:label cssClass="control-label" path="">
        <spring:message code="web.messages.someMessage" />
    </form:label>
    <form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
  <label>&nbsp;</label>
  <button type="button" id="search-btn" class="btn" >
        <spring:message code="web.messages.buttonMessage" />
  </button>
</div>

The ajax in the script:

$("#search-btn").on("click", function(e) {
    e.preventDefault();
    showDialog("${pageContext.request.contextPath}");
});

function showDialog(baseContext) {
    var article = $('#articleId').val().replace(/\s+/g, "");

    if (article) {
        article = "?article=" + article;
    }

    $.ajax({
        type : "GET",
        url : "${pageContext.request.contextPath}/sync/getFilter" 
            + article,
        success : function(data) {
            onClickTable();
        }
    });
}

This is part of the java method, where the value turns into gibberish:

@RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public @ResponseBody ModelAndView getFilter(HttpServletRequest request) {       
    String article = (String) request.getParameter("article");
    .
    .

Solution

  • Fixed the problem by putting the information in a JSON and sending it like that. The changed made:

    The ajax in the script part of the jsp:

    function showDialog(baseContext) {
        var article = $('#articleId').val().replace(/\s+/g, "");
    
        var data = {
                "article": $('#articleId').val().replace(/\s+/g, ""),
                // other keys and values
                "lastKey": $('#lastValueId').val().replace(/\s+/g, "")
        }
    
        $.ajax({
            type : "POST",
            url : "${pageContext.request.contextPath}/sync/getFilter",
            data: data,
            success : function(data) {
                onClickTable();
            }
        });
    }
    

    The java method handling the data:

    @RequestMapping(value = "/getFilter", method = RequestMethod.POST)
    public @ResponseBody ModelAndView getFilter(SomeObject receivedData) {
            String article = receivedData.getArticle();
            // rest of the method
    

    Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.