过滤到转发索引页面

时间:2017-04-23 13:29:54

标签: java servlets tomcat7

我想制作一个过滤器,转发/WEB-INF/index.html请求应用程序看起来像这样

http://localhost:8080/basic-application-web

这是我的过滤器

public class RootFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getRequestURI().equals("/basic%2Dapplication%2Dweb/")) {
            req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {}
}

我的web.xml看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
         xmlns='http://java.sun.com/xml/ns/javaee'
         xmlns:web='http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd'
         xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaeeweb-app_2_5.xsd'
         id='basic_web' version='2.5'>
    <display-name>Basic web application</display-name>

    <servlet>
        <servlet-name>serviceServlet</servlet-name>
        <servlet-class>com.pack.ServiceServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>serviceServlet</servlet-name>
        <url-pattern>/messaging</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>rootFilter</filter-name>
        <filter-class>com.pack.RootFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>rootFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

然而,当我尝试使用URL直接访问tomcat(我使用它来部署战争)时,我不时会遇到一些奇怪的行为。basic-application-web无法找到root

虽然通过tomcat经理可以正常工作。问题是什么?可能是由于缺少{{1}} servlet?

1 个答案:

答案 0 :(得分:0)

我将index.html移到WEB-INF之外,所以基本上布局开始看起来像这样

webapp
    WEB-INF\web.xml
    index.html

并将filter调整为/index.html而不是WEB-INF/index.html

req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);

它有所帮助。