jsp重定向中文乱码解决方案(jsp设置编码过滤器)
原创
©著作权归作者所有:来自51CTO博客作者小诸葛的博客的原创作品,请联系作者获取转载授权,否则将追究法律责任
问题描述:
因功能需求,需要在servlet中重定向到另一个页面,但是,重定向后页面中文发生了乱码,这种情况是由于没有配置编码过滤器导致的,解决方法如下:

1、新增编码过滤器类
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 编码过滤器
* @author Administrator
*
*/
public class EncodingFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2、在web.xml文件中配置此过滤器
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>demo.web.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>