【问题标题】:How to Support both index.html and "/" Servlet Mapping如何同时支持 index.html 和 "/" Servlet 映射
【发布时间】:2018-03-27 14:06:44
【问题描述】:

我的 Java Web 应用程序的根目录中有以下两个 servlet 和一个 index.html 页面。 index.html 页面收集一些数据并使用 Insert servlet 将其插入,然后为用户提供一个 URL 来检索数据(即http://localhost:8080/12345)。我希望用户能够在浏览器中输入http://localhost:8080/12345 并调用 Retrieve servlet。

现在发生的是当我输入http://localhost:8080http://localhost:8080/ 时,Retrieve servlet 被调用(它映射到 web.xml 中的“/”)。我只想在请求 http://localhost:8080/some_data_here 时调用 Retrieve servlet。任何想法如何修改 servlet 映射以支持这些要求?

index.html

<html>
   <body>
      <form action = "insert" method = "POST">
         Enter Data: <input type = "text" name = "data">
         <br />
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

WEB.XML

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>
        <servlet-name>Insert</servlet-name>
        <servlet-class>com.servlets.Insert</servlet-class>
        <load-on-startup>-1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Insert</servlet-name>
        <url-pattern>/insert</url-pattern>
    </servlet-mapping>
     <servlet>
        <servlet-name>Retrieve</servlet-name>
        <servlet-class>com.servlets.Retrieve</servlet-class>
        <load-on-startup>-1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Retrieve</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
         <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app> 

【问题讨论】:

    标签: java servlets web.xml


    【解决方案1】:

    如您所说,不要将Retrieve servlet 映射到/ 而是映射到/12345,然后将Insert servlet 之后的请求重定向到/12345

    【讨论】:

    • 您将如何映射到 /USER-ENTERED-DATA,因为 12345 是我根据用户输入的内容生成的数据库 ID。我需要留在 index.html 页面上并显示localhost:8080/USER-ENTERED-DATA(即/12345)
    • 如果你使用相同的路径 (/) 来处理不同的 servlet,那么你必须构建一个额外的 servlet/filter,它分析 URL,然后决定哪个要调用的 servlet(例如,通过将请求转发到另一个 (Retrieve) servlet 正在侦听的路径)。
    猜你喜欢
    • 2012-01-17
    • 2012-01-26
    • 1970-01-01
    • 2015-06-09
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多