所以我有这个非常简单的 html 文件:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form method="post" action="formpost.do" accept-charset="utf-8">
<label for="id">Your name please:</label>
<input id="id" type="text" name="name"/>
<input type="submit"/>
</form>
</body>
</html>
和输出.jsp:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<%= request.getAttribute("name") %>
</body>
</html>
当我在表单中输入“ğğğ”时,我在output.jsp 中看到了“ğğğ”。处理此表单的 Servlet 如下所示:
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletRequest.setCharacterEncoding("UTF-8");
String name = httpServletRequest.getParameter("name");
httpServletRequest.setAttribute("name",name);
PrintWriter printWriter = new PrintWriter(new File("C:/text.txt"));
printWriter.write(name);
printWriter.flush();
printWriter.close();
httpServletRequest.getRequestDispatcher("/output.jsp")
.forward(httpServletRequest, httpServletResponse);
}
问题是,在 text.txt 文件中我会看到“???”而不是“ğğğ”。我已经尝试解决这个问题几个小时了,但没有成功..
我有
JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8
在Windows环境变量中,但据我所知它没有改变。
当我调试此应用程序时,变量“name”在调试器窗口中被视为“ğğğ”(如果有帮助的话)。
那么如何才能让System.out打印出正确的字符呢?
编辑 1 当我创建一个单独的 Java 项目并简单地运行时:
public static void main(String[] args)
throws Exception {
PrintWriter printWriter = new PrintWriter(new File("C:/text.txt"));
printWriter.write("ğğğ");
printWriter.flush();
printWriter.close();
}
文本文件中的一切都符合预期。
编辑2 我的 server.xml 中已经有:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
最佳答案
我不认为这是 Tomcat 的问题。这是 Java 写入文件方式的问题。
书写时使用适当的字符集。
PrintWriter printWriter = new PrintWriter(new File("C:/text.txt"), "UTF-8");
显然还有阅读。
关于java - 如何告诉 Tomcat 在内部使用 UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23044976/