【问题标题】:Path in form tag action attribute表单标记动作属性中的路径
【发布时间】:2014-02-13 11:01:56
【问题描述】:

在 jsp 中考虑以下表单标签:

<form action="/sampleServlet" method="get">

有什么区别

<form action="/sampleServlet" method="get">

<form action="sampleServlet" method="get"> <!--no leading slash-->

【问题讨论】:

  • 问题是如果您使用 /sampleServlet,那么它将使用当前路径 + /sampleServlet,因此调用将转到应用程序中的映射 servlet 之一。如果仅使用 sampleServlet,则 url 本身将更改为 sampleServlet 无效并导致错误
  • 您的评论与 Alexandre 在 http://stackoverflow.com/questions/16683877/form-action-sampleservlet-giving-me-exception 中给出的答案相矛盾

标签: java jsp jakarta-ee servlets


【解决方案1】:

代码&lt;form action="/sampleServlet" method="get"&gt; 将提交表单并调用web.xml 中别名/sampleServlet 映射的servlet 的doGet()

在后面的情况下提交会抛出错误(可能是 404)。

【讨论】:

    【解决方案2】:

    /sampleServlet - 绝对路径

    此路径是基本 url(协议、ip(或主机名)和端口)的绝对路径

    current page: http://127.0.0.1:8080/context/test
    
    target page:  http://127.0.0.1:8080/sampleServlet
    

    sampleServlet - 相对路径

    这个路径是相对于当前页面的路径,例如

    current page: http://127.0.0.1:8080/context/test
    
    target page:  http://127.0.0.1:8080/context/test/sampleServlet
    

    在 JSP 中您应该使用绝对路径,但请记住自动添加上下文路径并考虑 url 重写(必要时将会话 id 添加到 url)。

    使用 JSTL 时,请使用 :

    <form action="<c:url value="/sampleServlet"/>" method="get">
    ...
    </form>
    

    【讨论】:

      猜你喜欢
      • 2014-06-15
      • 1970-01-01
      • 2020-01-10
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2021-07-30
      相关资源
      最近更新 更多