我想使用 javascript 将 Unicode 发送到 JSP 页面。我浏览了互联网,但仍然找不到答案。它总是向我显示类似'???? ????'。谁能告诉我答案。
这是我在 Controller 中的方法
@RequestMapping(value = "/conv", method = RequestMethod.POST)
public @ResponseBody
String add(@RequestParam(value = "input", required = true) String input) throws UnsupportedEncodingException {
String result = Run.getTranslation(input);
log.info(result);
byte[] bytesInUTF8 = result.getBytes("UTF-8");
String stringUsingUTF8 = new String(bytesInUTF8, "UTF-8");
return stringUsingUTF8;
}
这是我的 JavaScript 代码 (test.js)
$(document).ready(function(){
$("#submit").click(function(){
var input = $("#in").val();
$.ajax({
type : "POST",
url : "conv",
data : "input=" +input,
//contentType: 'text/plain; charset=utf-8',
success : function(response) {
$("#out").val(response)
},
error : function(e) {
alert('Error msg: ' + e);
}
});
});
$("#clear").click(function(){
$("#out").val("");
$("#in").val("");
});
});
这是我的 JSP 页面
<Doctype html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="<c:url value="/resources/js/jquery.min.js"/>"></script>
<script src="<c:url value="/resources/js/test.js"/>"></script>
<!-- You can add resources to page like above, .css and .js should be in resources folder -->
</head>
<body>
<h1>Translator</h1>
<h4>Input</h4>
<textarea id="in" rows="5" cols="100"></textarea>
<br>
<h4>Output</h4>
<textarea id="out" rows="5" cols="100"></textarea>
<br><br>
<button id="clear"> Clear</button> <button id="submit"> Convert</button>
</body>
</html>
最佳答案
byte[] bytesInUTF8 = result.getBytes("UTF-8");
String stringUsingUTF8 = new String(bytesInUTF8, "UTF-8");
这采用翻译后的 Unicode 字符串,使用 UTF-8 编码将其编码为字节,然后使用相同的编码将其解码回字符串。这是一个往返,stringUsingUTF8
将始终与 result
完全相同,因此您可以放弃它。
return stringUsingUTF8;
从 Spring @ResponseBody
方法返回的字符串使用 Servlet 的默认编码进行编码以发送到浏览器。 XMLHttpRequest 默认需要 UTF-8,但由于 Servlet 陈旧且糟糕,该编码不是 UTF-8 而是 ISO-8859-1,这几乎不是您想要的。
要解决此问题,您可以设置自定义 AnnotationMethodHandlerAdapter
。 About this.
请注意,您的输入也使用 Servlet 默认值 ISO-8859-1 进行解码。如果您需要接受非 ASCII 输入和输出,则需要在 web.xml 中设置 CharacterEncodingFilter
。 About this. (注意 multipart POST 表单和 GET 表单更复杂。Servlet 中的字符编码确实是一件非常可悲的事情。)
data : "input=" +input,
这应该是 encodeURIComponent(input)
,或者只是 data: {input: input}
让 jQuery 为您处理。否则像 &
和 %
这样的字符会被破坏。
关于java - 如何使用 JavaScript 在 Spring MVC 中获取对 JSP 的 Unicode 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25992431/