2013-10-22 102 views
1

在Spring MVC應用程序中,我有一個帶有Ajax的控制器和JSP文件。當我從Ajax發送數據到Spring Controller時,我有正確的字符串和字符集UTF-8,但是當控制器發送對Ajax的響應時,這個字符串的編碼是錯誤的。我需要控制器發送俄語響應,並有這個問題,當我有一個Ajax的響應並將其插入到JSP頁面我只有:?????? ????? ?????? 。這裏是我的代碼:Spring MVC。對Ajax的響應

@Controller 
public class GroupsController { 

@RequestMapping(value = "/addData.html", method = RequestMethod.GET) 
public ModelAndView getPage() { 
    return new ModelAndView("addData"); 
} 

@RequestMapping(value = "/addData.html", method = RequestMethod.POST) 
public @ResponseBody String addNewGroup(@ModelAttribute(value = "group") GroupStudent group, 

    if(group.getGroupStudentNumber() != null) { 
     return "Группа " + group.getGroupStudentNumber() + " добавлена"; 
    // return "Group " + group.getGroupStudentNumber() + " has been added"; 

    } else 
     return null; 

} 

} 


<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
<html> 
<head> 
    <title>Add data</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" charset="UTF-8"> 
    <script type="text/javascript" 
      src="<c:url value="resources/jquery.js"/>"></script> 
    <script type="text/javascript"> 
     function addGroupAjax() { 
      var groupStudentNumber = $('#groupStudentNumber').val(); 

      $.ajax({ 
       type: "POST", 
       url: "/IRSystem/addData.html", 
       data: "groupStudentNumber=" + groupStudentNumber, 

       success: function(response) { 
        $('#group').html(response); 
       }, 
       error: function(e) { 
        alert("Error" + e); 
       } 
      }); 
     } 
</script> 
</head> 
<body> 
       <div align="left"> 
        <label>Group</label> 
        <input id="groupStudentNumber"/> 
        <input type="submit" value="Add" onclick="addGroupAjax()" /> 
        <div id="group" style="color:green"></div> 
       </div> 

</body> 
</html> 

回答

0

您可以設置在RequestMapping頭這樣的編碼...

@RequestMapping(value = "/addData.html", method = RequestMethod.GET, produces = "charset=UTF-8") 

看看是否有幫助。

+0

不幸的是,它沒有幫助。 – Vlad

0

看起來好像你的AJAX處理程序沒有以UTF-8讀取響應主體。我不知道爲什麼。您可以嘗試通過在Spring生成的響應中指定內容類型來強制它。更改退貨類型

@RequestMapping(value = "/addData.html", method = RequestMethod.POST) 
public ResponseEntity<String> addNewGroup(@ModelAttribute(value = "group") GroupStudent group, ... 

    if(group.getGroupStudentNumber() != null) { 
     HttpHeaders headers = new HttpHeaders(); 
     headers.add("Content-Type", "text/html; charset=utf-8"); 
     ResponseEntity<String> entity = new ResponseEntity<String>("Группа " + group.getGroupStudentNumber() + " добавлена", headers, HttpStatus.OK); 
     return entity; 
    } else 
     return null; 
} 
+0

是的,它的工作。但我也找到了另一個解決方案。 \t <屬性名= 「了MessageConverter」> \t \t \t <屬性名=」 supportedMediaTypes」值= 「text/plain的;字符集= UTF-8」/> \t \t \t \t – Vlad