在JSP中使用@WebServlet url模式注释进行映射 [英] Map with @WebServlet url pattern annotation in JSP
问题描述
当试图制作一个简单的Webservlet时,偶然发现了这个问题:如果我使用包含/../的名称,它将找不到资源.
When trying to make a simple webservlet a stumble upon this problem: if I use a name that includes /../ it won't find the resource.
这就是我的工作方式
Controller.java
Controller.java
@WebServlet(urlPatterns = {"/Controller"})
public class Controller extends HttpServlet{ ... }
和JSP页面:
<form action="Controller">
...
</form>
但是,我尝试将名称指定为文件夹,以使结构更加结构化.这是我苦苦挣扎的代码,但无效:
However, what I try to do specify the name as a folder, to work more structured. This is the code I struggle with and that DOESN'T work:
@WebServlet(urlPatterns = {"/servletController/Controller"})
public class Controller extends HttpServlet{ ... }
JSP页面:
<form action="/servletController/Controller">
...
</form>
我尝试了多种变体.所以我的问题是,如何正确使用带有urlPatters-annotation的文件夹结构,还是不可能?
And I tried numerous variations. So my question, how to properly use a folder-structure with the urlPatters-annotation, or is it just not possible?
推荐答案
这是由您在<form action>
中指定的前导斜杠引起的.它使指定的URL是相对域的. IE.相对于您在浏览器地址栏中看到的URL中的域根目录,而不是相对于您在浏览器地址栏中看到的URL中当前请求的路径(文件夹),它是解析的.
It's caused by the leading slash you specified in the <form action>
. It makes the specified URL domain-relative. I.e. it's resolved relative to the domain root in the URL as you see in browser's address bar, instead of to the currently requested path (folder) in the URL as you see in browser's address bar.
想象一下,您的JSP是通过以下方式打开的:
Imagine that your JSP is opened by
http://localhost:8080/contextname/some.jsp
,因此URL中包含文件夹/contextname
.您将提交给
and the URL has thus the folder /contextname
in it. The form action as you have would submit to
http://localhost:8080/servletController/Controller
而servlet是根据您的映射实际上在以下URL上进行的:
while the servlet is as per your mapping actually at the following URL:
http://localhost:8080/contextname/servletController/Controller
相应地修复表单操作,使其相对于路径而不是相对于域:
Fix the form action accordingly to make it path-relative instead of domain-relative:
<form action="servletController/Controller">
或者,通过指定有效的相对于域的URL:
Or, by specifying a valid domain-relative URL:
<form action="/contextpath/servletController/Controller">
或者,如果您担心上下文路径的动态性,而又不想对其进行硬编码:
Or, if you worry about the dynamicness of the context path and rather like not to hardcode it:
<form action="${pageContext.request.contextPath}/servletController/Controller">
另请参见:
- 在调用转发到JSP的Servlet时,浏览器无法访问/查找CSS,图像和链接等相对资源
- Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
See also:
这篇关于在JSP中使用@WebServlet url模式注释进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!