当前位置:编程学习 > JAVA >>

过滤器报错:Filter cannot be cast to javax.servlet.Servlet

启动页面报错是什么原因:java.lang.ClassCastException: chen.wei.EncodingFilter cannot be cast to javax.servlet.Servlet
【xml配置】
<filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>
   chen.wei.EncodingFilter
  </filter-class>
  <init-param>
   <param-name>Encoding</param-name>
   <param-value>utf-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>EncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping> 
【过滤器代码】
package chen.wei;

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 EncodingFilter implements Filter {
 protected FilterConfig config;
 protected String Encoding = null;
 public void init(FilterConfig config) throws ServletException {
  this.config = config;
  this.Encoding = config.getInitParameter("Encoding");
 }
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  if (request.getCharacterEncoding() == null) {
   if (Encoding != null) {
    request.setCharacterEncoding(Encoding);
    response.setCharacterEncoding(Encoding);
   }
  }
  chain.doFilter(request,response);
 }
 public void destroy() {}
}
【jar包】
jre和Java ee6 --------------------编程问答-------------------- ServletRequest request, ServletResponse response
用的时候转化为HttpServletRequest... --------------------编程问答-------------------- 你的servlet-api.jar与tomcat里的servlet-api.jar有冲突,你项目里的servlet-api.jar包没必要有,或者不要加入到构建路径里去 --------------------编程问答-------------------- request.getCharacterEncoding() == null用了这句就要转化为HttpServletRequest
补充:Java ,  Web 开发
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,