在Spring MVC Application中,我有一个带Ajax的控制器和JSP文件。当我将数据从Ajax发送到Spring Controller时,我有正确的字符串和charset UTF-8,但是当控制器向Ajax发送响应时,这个字符串的编码是错误的。我需要控制器以俄语发送响应并且遇到这个问题,当我对Ajax做出响应并将其插入JSP页面时我只有:?????? ????? ??????这是我的代码:
@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 :(得分:0)
您可以像这样设置RequestMapping标头中的编码......
@RequestMapping(value = "/addData.html", method = RequestMethod.GET, produces = "charset=UTF-8")
看看是否有帮助。
答案 1 :(得分: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;
}