首先由下圖看一下filter的原理圖
javaWeb解決中文亂碼的配置網上一大推,此處不再贅述;此處只實現自定義的filter來對request請求和response響應做相應的編碼控制,詳見下列代碼
package com.medicine.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 字符編碼過濾器
*
* @author wk
*
*/
public class CharacterEncodingFilter implements Filter {
protected String encoding = null;
protected String resType = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
@Override
public void destroy() {
// 銷燬所有全局變量的值,設爲null
this.encoding = null;
this.filterConfig = null;
this.resType = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// 從web.xml中得到過濾器的字符串編碼
if (ignore || (request.getCharacterEncoding() == null)) {
if (encoding != null) {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
response.setContentType(resType);
}
}
filterChain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
this.resType = filterConfig.getInitParameter("resType") == null ? "text/html; charset=utf-8"
: filterConfig.getInitParameter("resType");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else
this.ignore = false;
}
}
web.xml中配置如下:
<span style="white-space:pre"> </span><filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.medicine.web.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>resType</param-name>
<param-value>text/html; charset=utf-8</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
當然其實Spring中已經爲我們提供了org.springframework.web.filter.CharacterEncodingFilter來專門解決中文亂碼的問題,但是查看它的源碼
<span style="white-space:pre"> </span>@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
可以發現它只對response進行了相應編碼卻沒有對響應頭進行處理,所以這也是我選擇自定義filter的原因