中文过滤器---Filter

阅读更多
  在jsp页面传接收中文字符时,常常会出现乱码问题,解决起来很简单,只要加一个中文过滤器的类就可以,值得注意的是,此类是实现Filter类,所有起类名时要与其有区别才 可以(例如:EncodingFilter),简单代码如下:
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;

/**
* 编码过滤器, 默认UTF-8
*
* @author linde13652
*
*/

public class EncodingFilter implements Filter {

private String encoding = "UTF-8";

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding( this. encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
String encoding = config.getInitParameter(" encoding");

if (encoding != null && encoding.trim().length() > 0) {
this. encoding = encoding;
}
}

}

你可能感兴趣的:(Servlet,JSP)