Chinese Version:开发基于JBoss AS 7.2.0的Java EE程序 - 08.如何设置UTF-8 or 开发基于JBoss AS 7.2.0的Java EE程序 - 08.如何设置UTF-8
Summary
To support Multilingual(for example, English, Chinese, Japanese...) in our application, we have many places to configure UTF-8 encoding.
1. MySql Data Encoding Setting
Please refer to 链接 in CentOS 6.4安装MySql Server和Client,设置字符集为UTF-8,修改登陆密码
2. ServletRequest and ServletResponse Encoding
Let's create a servlet filter to set the encoding of ServletRequest and ServletResponse to UTF-8.
package com.ybxiang.forum.servlet.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* http://bbs.csdn.net/topics/300037688
* @author yingbinx
*
*/
@javax.servlet.annotation.WebFilter("/*")
public class EncodingFilter implements Filter {
static final Logger logger = Logger.getLogger(EncodingFilter.class.getName());
//FilterConfig config;
public void doFilter(ServletRequest r1, ServletResponse r2, FilterChain chain)throws ServletException,IOException {
HttpServletRequest request = (HttpServletRequest)r1;
HttpServletResponse response = (HttpServletResponse)r2;
try {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
logger.severe(e.getMessage());
}
//WARNING: do NOT swallow any Exception!!! If container can not see any exception, it will not redirect client to related error page.
//You can catch Exceptions and print them, and you must throw them at last!
chain.doFilter(r1, r2);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig arg0) throws ServletException {
//config = arg0;
}
}
3. ServletResponse encoding
If we want to set encoding for specific servlet response, we can do it like this:
@WebServlet("/UploadPortraitServlet")
public class UploadPortraitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
....
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
...
}
...
}
4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>PARAMETER_ENCODING</param-name>
<param-value>UTF-8</param-value>
</context-param>
<!-- Production,Development,UnitTest,SystemTest,Extension -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
...
}
5. JAAS authenticator encoding setting in jboss-web.xml
If bellow JAAS authenticator's encoding is NOT set and username contains Chinese character, login will fail.
So, let's set it in jboss-web.xml too:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<security-domain>java:/jaas/ybxiang-forum-jaas-security-domain</security-domain>
<!-- encoding for login servlet 'j_security_check' -->
<valve>
<class-name>org.apache.catalina.authenticator.FormAuthenticator</class-name>
<param>
<param-name>characterEncoding</param-name>
<param-value>UTF-8</param-value>
</param>
</valve>
</jboss-web>
6. faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
...
</faces-config>
7. JSF pages
(a) Generic pages
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
...
</html>
(b) component page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
...
</ui:composition>
8. JSF MBean中解析URL中的UTF-8参数
If we access bellow links in JSF MBean:
http://javaarm.com/faces/list.xhtml?mid=42&keywords=介绍
or
http://javaarm.com/faces/list.xhtml?mid=42&keywords=%E4%BB%8B%E7%BB%8D
, then we should decoding this parameter 'keywords' in the JSF MBean.
@ManagedBean
@RequestScoped
public class TopicGroupingPagerMBean extends AbstractPagerMBean{
static final Logger logger = Logger.getLogger(TopicGroupingPagerMBean.class.getName());
...
public final String getKeywords(){
String keywords = ...;
if(keywords==null || keywords.trim().length()==0){
return "";
}
try{
keywords = java.net.URLDecoder.decode(keywords, "UTF-8");
}catch(Exception e){
Log.error(e);
}
return keywords;
}
...
}
9. UTF-8 setting in JBossAS7 standalone.xml
(a) JAAS hashCharset
<subsystem xmlns="urn:jboss:domain:security:1.2">
<security-domains>
<security-domain name="ybxiang-forum-jaas-security-domain" cache-type="default">
<authentication>
<login-module code="Remoting" flag="optional">
<module-option name="password-stacking" value="useFirstPass"/>
</login-module>
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
<module-option name="password-stacking" value="useFirstPass"/>
<module-option name="dsJndiName" value="java:jboss/datasources/ybxiangForumMySqlDataSource"/>
<module-option name="principalsQuery" value="SELECT hashedPassword FROM User WHERE username=? and activated=true and locked=false"/>
<module-option name="rolesQuery" value="SELECT DISTINCT r.name, 'Roles' FROM User u, User_UserGroup ug, UserGroup_JaasRole gr, JaasRole r WHERE u.id=ug.user_id AND ug.usergroup_id=gr.usergroup_id AND gr.jaasrole_id=r.id AND u.username=?"/>
<module-option name="hashAlgorithm" value="SHA-256"/>
<module-option name="hashEncoding" value="Base64"/>
<module-option name="hashCharset" value="UTF-8"/>
<module-option name="unauthenticatedIdentity" value="guest"/>
</login-module>
</authentication>
</security-domain>
...
...
...
Comments