我們在用JSP做Web項目是會遇到中文無法顯示的問題.
在Servlet中會用request.setCharacterEncoding("gb2312");(request為HttpServletRequest的對象)來處理.
每一個Servlet都要這樣去做很麻煩.
下面介紹用過濾器來處理這種問題,簡單方便,不需要重複寫.
1.首先寫一個EncodingFilter.java
package aa;
import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter
{
protected String encoding = null;
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
//從web.xml設定檔中擷取編碼配置
this.encoding = filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
if(request.getCharacterEncoding() == null)
{
String encode = getEncoding();
if(encode != null)
{
//設定request的編碼方式
request.setCharacterEncoding(encode);
}
}
chain.doFilter(request,response);
}
public String getEncoding()
{
return encoding;
}
public void destroy()
{
}
2.在web.xml檔案中配置一下,添加下面內容
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>aa.EncodingFilter</filter-name>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.重啟服務,問題解決。