任何人都可以给我有关设置 URL 模式的规则的信息,以及我是否使用 /
作为索引页,并且我还需要使用 request.getRequestDispatcher("/html/file .html").forward(请求,响应)
.
文件file.html
位于war
文件夹下的html
文件夹中,html
文件夹位于WEB-INF
有人可以给我建议吗? 谢谢
最佳答案
您可以在 web.xml 中定义一个 servlet,如下所示,然后使用 request.getRequestDispatcher("file").forward(request,response)
,本质上会发生的情况是:将您的请求分派(dispatch)到映射为 /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映射:
假设您想要定义,如果映射与任何servlet 映射都不匹配,则应将其映射到默认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 规范的摘要图:
关于java - web.xml URL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588884/