我们在用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.重启服务,问题解决。