急!字符编码过滤器问题!!!
加个过滤器,但是没效果,发现doFilter()方法根本没执行!init()方法执行了!web.xml没配置错!这是为什么?
[code=Java][/code]
MyFilter.java
package com.duyuan;
import
java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import
javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter implements Filter {
private String encoding=null;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws
IOException,
ServletException {
System.out.println("Filter執行!!!");
HttpServletRequest req=(HttpServletRequest)arg0;
HttpServletResponse res=(HttpServletResponse)arg1;
if(encoding!=null){
req.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
res.setContentType("text/html;charset="+encoding);
}
arg2.doFilter(req, res);
}
public void init(FilterConfig arg0) throws ServletException {
encoding=arg0.getInitParameter(encoding);
System.out.println("Filter初始化!!!");
}
}
------解决方案--------------------
你确定你的配置没错么??我之前写的一段代码,可以用,你试试!
package com.jy.util;
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;
public class CharacterFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding("gbk");
arg1.setCharacterEncoding("gbk");
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}