filter - 为什么将过滤器添加到 web.xml 会导致 404 错误?
问题描述
为了学习/练习使用 struts 2,我使用了 struts2-archetype-starter maven 原型。
我在尝试添加自己的过滤器时遇到了问题,希望有人能指出我正确的方向。
我在构建过程中使用 eclipse 和 maven,并使用 Tomcat 8.5 作为 localhost 服务器。
我已经能够设置一些基本操作。我现在正在尝试添加一个过滤器来设置请求的编码,以便我可以处理日语输入。为此,我引用了有关过滤器的资源,以创建我自己的自定义过滤器,我在项目的 web.xml 文件中引用了该过滤器
过滤器参考来源:https ://www.oracle.com/java/technologies/filters.html
但是,当我尝试访问我的项目的 url 时,我收到 404 错误。
我尝试在我的过滤器中添加断点并在服务器上调试项目,但断点从未被命中。(否则我可以调试和使用断点)
在我的 web.xml 文件中,我添加了过滤器声明:
<filter>
<filter-name>MyEncoder</filter-name>
<filter-class>jono_group.mav_arch_2.filters.MyChaEnFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>Shift_JIS</param-value>
</init-param>
</filter>
和这个过滤器映射
<filter-mapping>
<filter-name>MyEncoder</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
它们分别位于所有其他过滤器和过滤器映射的前面,目的是在过滤器链的前面执行。
使用上述过滤器和过滤器映射,maven build (clean package 运行成功,没有报告错误。但我得到了 404。一旦我删除它们,404 错误就会消失,我的操作按预期工作。
任何帮助将不胜感激。
我的过滤器类如下:
package jono_group.mav_arch_2.filters;
import java.io.IOException;
import java.nio.file.DirectoryStream.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyChaEnFilter implements Filter
{
private FilterConfig filterConfig = null;
private String encoding;
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain) throws
IOException, ServletException {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws
ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
public void destroy() {
this.filterConfig = null;
}
@Override
public boolean accept(Object entry) throws IOException {
// TODO Auto-generated method stub
return false;
}
}
解决方案
import java.nio.file.DirectoryStream.Filter
不是 servlet 过滤器。
从您提供的链接,特别是从编程过滤器部分:
过滤器 API 由javax.servlet 包中的 、 和 接口
Filter
定义FilterChain
。FilterConfig
FilterChain
并且FilterConfig
正确导入,Filter
而不是那么多。
推荐阅读
- google-sheets - 如何向左列转置行到列?在 Google 表格中
- android - React Native AppState onChange 事件不适用于启动画面(仅限 Android)
- angular - Angular - 找不到模块“文件保护程序”的声明文件
- c# - 如果“值类型”变量仍在被另一个线程使用(由“ref”传递),那么在离开方法范围时如何从堆栈中释放它?
- haskell - Haskel - Gloss:平铺表(或如何从图片中提取区域)
- google-apps-script - 用于显示/隐藏工作表的按钮中的 Google Apps 脚本
- java - 我需要正确发送请求,但我不知道如何从对象中获取所需的值
- php - 根据作者 ID 更改帖子 URL
- android - Flutter 如何获取可迭代的 .toList() 列表的长度?
- git - 从 git 分支的历史记录中删除某些提交