首页 > 解决方案 > 为什么将过滤器添加到 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;
    }
}

标签: filterstruts2http-status-code-404

解决方案


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

从您提供的链接,特别是从编程过滤器部分:

过滤器 API 由javax.servlet 包中的 、 和 接口Filter定义FilterChainFilterConfig

FilterChain并且FilterConfig正确导入,Filter而不是那么多。


推荐阅读