<%@ page language="java" pageEncoding="GBK" %>
或使用 contentType:
<%@ page contentType="text/html;charset=gbk" %>
GBK 比 GB2312 支援更多字符,建議優先使用。此法適用於 JSP 頁面本身的中文顯示。
Tomcat 預設採用 ISO-8859-1 編碼處理請求,導致中文參數變亂碼。編寫 SetCharacterEncodingFilter 過濾器可強制指定請求編碼:
import java.io.IOException;
import javax.servlet.*;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null) this.ignore = true;
else if (value.equalsIgnoreCase("true")) this.ignore = true;
else this.ignore = false;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null) request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
protected String selectEncoding(ServletRequest request) {
return this.encoding;
}
}
在 web.xml 註冊:
<!-- SetCharacterEncoding -->
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>com.struts.common.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- SetCharacterEncoding -->
優點:專案層級統一處理,支援國際化(頁面指定 pageEncoding="UTF-8" 即可依 Locale 顯示正確字符集),強烈推薦。
<Connector port="80" URIEncoding="GBK" ... />
Tomcat 5.0+ 版本中,GET 與 POST 處理編碼方式不同,若從 URL 取得中文參數會出現問號。修改 URIEncoding 可解決 GET 請求中文亂碼問題(Tomcat 4.1 無此問題)。