我在用MyEclipse练习Filter,出现类型转换的问题,大家帮忙看看
下面给出源代码。
ChiniseFilter.java
public class ChiniseFilter implements Filter{
public void init(FilterConfig config) throws ServletException{}
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws ServletException,IOException{
//将所有request内的对象设置字符集为UTF-8
HttpServletRequest request=(HttpServletRequest)req;
request.setCharacterEncoding("UTF-8");
//将所有response内的对象设置字符集为UTF-8
HttpServletResponse response=(HttpServletResponse)res;
response.setCharacterEncoding("UTF-8");
//用chain的doFilter处理过滤
chain.doFilter(request, response);
}
public void destroy(){}
}
web.xml
<filter>
<filter-name>ChiniseFilter</filter-name>
<filter-class>com.myfilter.ChiniseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ChiniseFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
filter_chinise.jsp
<body>
<%
String username="无极";
String sex="男";
String addr="地球";
request.setAttribute("username",username);
request.setAttribute("sex",sex);
request.setAttribute("addr",addr);
request.getRequestDispatcher("filter_chinise_get.jsp").forward(request,response);
%>
</body>
filter_chinise_get.jsp
<body>
username的值:<%=request.getAttribute("username") %> <br />
sex的值:<%=request.getAttribute("sex") %> <br />
addr的值:<%=request.getAttribute("addr") %>
</body>
出现的错误:
java.lang.ClassCastException: com.myfilter.ChiniseFilter cannot be cast to javax.servlet.Filter
------解决方案--------------------
public class ChiniseFilter implements Filter
这里implements的Filter,是不是 javax.servlet.Filter ?
看看你文件前面的 import 是啥?
------解决方案--------------------
这个好奇怪、、、、mark
------解决方案--------------------
说你写的这个类不能投射到java.servlet.Filter这个接口,你是不是继承的不是这个接口啊
------解决方案--------------------
看看你的web-inf\classes文件下有没有 ChiniseFilter.class 文件。