【问题标题】:web.xml URL patternweb.xml URL 模式
【发布时间】:2017-11-19 05:01:56
【问题描述】:
谁能给我有关设置 URL 模式的规则的信息,如果我使用 / 作为我的索引页面,并且我还需要使用 request.getRequestDispatcher("/html/file.html").forward(request,response)。
文件file.html位于war文件夹下的html文件夹中,html文件夹与WEB-INF在同一文件夹中
谁能给我建议?
谢谢
【问题讨论】:
标签:
java
html
servlets
web.xml
url-pattern
【解决方案1】:
您可以在 web.xml 中定义一个 servlet,如下所示,然后使用 request.getRequestDispatcher("file").forward(request,response),本质上,您会将请求发送到映射为 /file 的 servlet,并且该 servlet 会将您指向你的资源/html/file.html。请注意,即使元素名称是 jsp-file,但您可以从中指向 HTML。
<servlet>
<servlet-name>FileServlet</servlet-name>
<jsp-file>/html/file.html</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file</url-pattern>
</servlet-mapping>
作为一个附加组件——关于 URL 模式如何匹配 web.xml 文件中的 servlet 映射,下面是 web.xml 中的 servlet 映射规则(来源是 - Servlet specs 和 @BalusC answer):
1.路径映射:
-
如果您想创建路径映射,则以/ 开始映射,并以/* 结束它。例如:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/foo/bar/*</url-pattern> <!-- http://localhost:7001/MyTestingApp/foo/bar/index.html would map this servlet -->
</servlet-mapping>
2。扩展映射:
-
如果您想创建扩展映射,请使用 servlet 映射 *.。例如:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>*.html</url-pattern> <!-- http://localhost:7001/MyTestingApp/index.html would map this servlet. Also, please note that this servlet mapping would also be selected even if the request is `http://localhost:7001/MyTestingApp/foo/index.html` unless you have another servlet mapping as `/foo/*`. -->
</servlet-mapping>
3.默认 servlet 映射:
-
假设您想定义,如果一个映射不匹配任何servelt 映射,那么它应该被映射到默认的servlet,然后servlet 映射为/。例如:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/</url-pattern> <!-- Suppose you have mapping defined as in above 2 example as well, and request comes for `http://localhost:7001/MyTestingApp/catalog/index.jsp` then it would mapped with servlet -->
</servlet-mapping>
4.精确匹配映射:
-
假设您要定义完全匹配映射,然后不使用任何通配符或其他内容,并定义完全匹配,例如/catalog。例如:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/catalog</url-pattern> <!-- Only requests with http://localhost:7001/MyTestingApp/catalog will match this servlet -->
</servlet-mapping>
5.应用上下文根映射:
-
空字符串"" 是一个特殊的 URL 模式,它完全映射到
应用程序的上下文根。即,http://localhost:7001/MyTestingApp/ 形式的请求。
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern></url-pattern> <!-- Only requests with http://localhost:7001/MyTestingApp/ will match this servlet Please note that if request is http://localhost:7001/MyTestingApp/abc then it will not match this mapping -->
</servlet-mapping>
6.匹配所有映射:
-
如果您想将所有请求匹配到一个映射或覆盖所有其他 servlet 映射,则创建一个映射为 /*。
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/*</url-pattern> <!-- This will override all mappings including the default servlet mapping -->
</servlet-mapping>
下面是JMS规范的总结图: