我一直在尝试为我的应用程序设置UTF-8编码。目前,它被设置为默认latin1。我已经浏览了几个博客,并按照其中的建议对JSP,glassfish-web.xml和mysql进行了必要的更改。我尝试通过使用latin1创建测试表然后将其转换为utf8来测试编码。我做了以下更改:
数据库表:
select * from test_latin;
+-------+
| c |
+-------+
| a |
| abc |
| © |
| Á |
| ß ö |
+-------+
select * from test_utf8;
+-------+
| c |
+-------+
| a |
| abc |
| © |
| Á |
| ß ö |
+-------+
将此添加到web.xml
<filter>
<filter-name>utf8EncodingFilter</filter-name>
<filter-class>gji.web.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>utf8EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在jsps中:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
在java代码中,我可以看到它们在日志中正确打印。但是在JSP上它显示为:
Info: utf-8 char:- a
Info: utf-8 char:- abc
Info: utf-8 char:- ©
Info: utf-8 char:- Á
Info: utf-8 char:- ß ö
Info: latin char:- a
Info: latin char:- abc
Info: latin char:- ©
Info: latin char:- Á
Info: latin char:- ß ö
LATIN:[a, abc, ツᄒᄅ, テᄒチ, テᄒ゚ テᄒᄊ]
UTF-8:[a, abc, ツᄒᄅ, テᄒチ, テᄒ゚ テᄒᄊ]
在glassfish配置中,我添加了设置以启用utf-8编码。同样添加了数据库连接的参数。
使用stackoverflow上的答案中的代码,我添加了一个过滤器来打印响应输出。响应输出显示以下内容:
<label>LATIN:</label>[a, abc, ツᄒᄅ, テᄒチ, テᄒ゚ テᄒᄊ]
<label>UTF-8:</label>[a, abc, ツᄒᄅ, テᄒチ, テᄒ゚ テᄒᄊ]
十六进制值和char变量值:
mysql> select c,length(c),char_length(c),charset(c), hex(c) from test_latin;
+-------+-----------+----------------+------------+--------+
| c | length(c) | char_length(c) | charset(c) | hex(c) |
+-------+-----------+----------------+------------+--------+
| a | 1 | 1 | latin1 | 61 |
| abc | 3 | 3 | latin1 | 616263 |
| © | 1 | 1 | latin1 | A9 |
| Á | 1 | 1 | latin1 | C1 |
| ß ö | 3 | 3 | latin1 | DF20F6 |
+-------+-----------+----------------+------------+--------+
mysql> select c,length(c),char_length(c),charset(c), hex(c) from test_utf8;
+-------+-----------+----------------+------------+------------+
| c | length(c) | char_length(c) | charset(c) | hex(c) |
+-------+-----------+----------------+------------+------------+
| a | 1 | 1 | utf8 | 61 |
| abc | 3 | 3 | utf8 | 616263 |
| © | 2 | 1 | utf8 | C2A9 |
| Á | 2 | 1 | utf8 | C381 |
| ß ö | 5 | 3 | utf8 | C39F20C3B6 |
+-------+-----------+----------------+------------+------------+
mysql> show variables like '%char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
我坚持这个。感谢您的指导。谢谢!