【发布时间】:2014-05-27 12:29:45
【问题描述】:
所以我有这个非常简单的 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>
还有 output.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"/>
【问题讨论】:
-
您使用什么来“查看 txt.file” - 您可能没有将该文件读取为 UTF-8 格式?
-
@MTilsted 请查看我的编辑。
标签: java jsp tomcat utf-8 character-encoding