【问题标题】:Why does adding filter to web.xml cause 404 error?为什么将过滤器添加到 web.xml 会导致 404 错误?
【发布时间】:2020-05-05 02:53:49
【问题描述】:

为了学习/练习使用 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;
    }
}

【问题讨论】:

    标签: filter struts2 http-status-code-404


    【解决方案1】:

    import java.nio.file.DirectoryStream.Filter 不是 servlet 过滤器。

    通过您提供的链接,特别是来自Programming Filters 部分:

    过滤器 API 由 javax.servlet 包中的 FilterFilterChainFilterConfig 接口定义。

    FilterChainFilterConfig 导入正确,Filter 没有那么多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多