本文介紹過濾器來設定字元編碼的問題,通過編寫一個servlet和配置web.xml來即可實現
這樣不必在每個jsp頁面社自豪字元編碼了,值需要在web.xml配置需要的編碼即可。
web.xml配置內容如下:
<!-- 字元過濾器 -->
<filter>
<filter-name>encodeFilter</filter-name>
<filter-class>
test.servlet.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter內容如下:
package test.servlet;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
protected String encoding = "UTF-8";
protected FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (request.getCharacterEncoding() == null) {
String encoding = selectEncoding(request);
if (encoding != null) {
request.setCharacterEncoding(encoding);
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
}
轉: 字元版面設定方式:
1. pageEncoding:<%@ page pageEncoding="UTF-8"%>
jsp頁面編碼: jsp檔案本身的編碼
2. contentType: <%@ page contentType="text/html; charset=UTF-8"%>
web頁面顯示編碼:jsp的輸出資料流在瀏覽器中顯示的編碼
3. html頁面charset:<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
web頁面輸入編碼: 輸入框輸入的字型編碼
4. setCharacterEncoding:request.setCharacterEncoding(),response.setCharacterEncoding()
web伺服器輸入的請求流: web Server相應瀏覽器的請求資料
5 .setContentType:response.setContentType()
web伺服器輸出的響應流: web Server相應瀏覽器的輸出資料
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/XinVSYuan/archive/2009/02/05/3864853.aspx