Skip to main content
 首页 » 编程设计

servlets之映射 servlet 来满足我的请求

2024年02月20日21pander-it

我想映射一个 servlet 来服务包含“app”并以 *.html 结尾的请求,方法如下

<url-pattern>/app/*.html</url-pattern> 

但是在运行应用程序时它给了我一个错误

java.lang.IllegalArgumentException: Invalid <url-pattern>  
/app/*.html in servlet mapping 

请帮我绘制一下。请提供我可以了解这些 url 映射规则和约定的链接。

请您参考如下方法:

这确实是无效的。通配符必须是第一个或最后一个字符,分别表示后缀或前缀模式。

<url-pattern>*.html</url-pattern> 

<url-pattern>/app/*</url-pattern> 

这在Servlet API specification的第12.2节中都有明确规定。 。以下是相关性摘录:

12.2 Specification of Mappings

In the Web application deployment descriptor, the following syntax is used to define mappings:

  • A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
  • A string beginning with a ‘*.’ prefix is used as an extension mapping.
  • The empty string ("") is a special URL pattern that exactly maps to the application's context root, i.e., requests of the form http://host:port/<contextroot>/. In this case the path info is ’/’ and the servlet path and context path is empty string (““).
  • A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  • All other strings are used for exact matches only.

要解决此问题,您有 2 个选择:

  1. 使用 /app/*模式,并且不要将非 HTML 文件放入 /app 中。将它们放在其他地方。

  2. 使用不同的前缀模式,例如 /controller/*并创建一个 Filter映射到 /app/*并在 doFilter() 中执行以下操作方法:

    String uri = ((HttpServletRequest) request).getRequestURI(); 
    if (uri.endsWith(".html")) { 
        request.getRequestDispatcher("/controller" + uri).forward(request, response); 
    } else { 
        chain.doFilter(request, response); 
    } 
    
<小时 />

相关: