简体   繁体   English

UTF-8无法通过JDBC在MySQL的Servlet中使用

[英]UTF-8 not working in Servlets with MySQL via JDBC

I have a Java Servlet running on a Tomcat Server with a MySQL database connection using JDBC. 我在使用JDBC的MySQL数据库连接的Tomcat服务器上运行Java Servlet。 If I have following piece of code works in, the hard-coded-HTML code works, but everything that comes from the database is displayed incorrectly. 如果可以使用以下代码,则可以使用硬编码的HTML代码,但是来自数据库的所有内容均显示不正确。

response.setContentType("text/html;charset=UTF-8")

在此处输入图片说明

If I remove the line the text from the database gets displayed correct, but not the basic HTML. 如果我删除该行,则数据库中的文本将正确显示,但基本HTML不会正确显示。 在此处输入图片说明

In the database, and Eclipse everything is set to UTF-8. 在数据库和Eclipse中,所有内容均设置为UTF-8。

On first sight it looks as if you were converting the text from the database again, once too much. 乍一看,好像您是在再次转换数据库中的文本一样,一次又一次。

So the first check is the database. 因此,首先检查的是数据库。 For instance the length of "löl" should be 3. Whether the data stored is correctly, read correctly. 例如,“löl”的长度应为3。是否正确存储了数据,请正确读取。 As @StanislavL mentioned, not only the database needs the proper encoding, in MySQL also the java driver that communicates needs to be told the encoding with ?useUnicode=yes&characterEncoding=UTF-8 . 正如@StanislavL所提到的,不仅数据库需要正确的编码,而且在MySQL中,还需要使用?useUnicode=yes&characterEncoding=UTF-8告知通信的Java驱动程序编码。 Maybe write or debug a small piece of code reading the database. 也许编写或调试一小段代码来读取数据库。

If stored correctly the culprit might be String.getBytes() or new String(bytes) . 如果存储正确,罪魁祸首可能是String.getBytes()new String(bytes)

In the browser inspect the encoding or save the pages. 在浏览器中检查编码或保存页面。 With a programmer's editor like NotePadd++ or JEdit inspect the HTML. 使用诸如NotePadd ++或JEdit之类的程序员的编辑器检查HTML。 These tools allow reloading with a different encoding, to see what the encodings are. 这些工具允许使用不同的编码重新加载,以查看编码是什么。

It should be that the first page is in UTF-8 and the second in Windows-1252 or something else. 应该第一页是UTF-8,第二页是Windows-1252或其他。

Ensure that the HTML source text is correct: you might use "\ü" for ü in a JSP. 确保HTML源文本正确:在JSP中,您可以在ü中使用“ \\ u00FC”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM