In Spring MVC Application I have a controller and JSP file with Ajax. When I send data from Ajax to Spring Controller I have correct string with charset UTF-8 but when controller sends response to Ajax the encoding of this string is wrong. I need controller to send response in Russian and have this problem, when I have a response to Ajax and insert it to JSP page I have only: ?????? ????? ?????? .Here's my code:
@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>
You can set the encoding in the RequestMapping header like this...
@RequestMapping(value = "/addData.html", method = RequestMethod.GET, produces = "charset=UTF-8")
See if that helps.
It seems like your AJAX handler isn't reading the response body as UTF-8. I don't know why. You can try to force it by specifying the content type in the response generated by Spring. Change your return type
@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;
}