0

I have the below two servlets and an index.html page in the root of my Java web app. The index.html page collects some data inserts it using the Insert servlet and then gives the user a URL to retrieve the data (i.e. http://localhost:8080/12345). I would like the user to be able to put http://localhost:8080/12345 in a browser and for the Retrieve servlet to get called.

What happens right now is when I enter in http://localhost:8080 or http://localhost:8080/ the Retrieve servlet gets called (it's mapped to "/" in the web.xml). I would only like to call the Retrieve servlet when http://localhost:8080/some_data_here is requested. Any ideas how to modify the servlet mappings to support these requirements?

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> 
c12
  • 9,557
  • 48
  • 157
  • 253

1 Answers1

1

What about not mapping the Retrieve servlet to / but to /12345 as you said and then redirect the request after the Insert servlet to /12345.

Niklas P
  • 3,427
  • 2
  • 15
  • 19
  • how would you map to /USER-ENTERED-DATA as 12345 is a DB ID that I generate based on what the user enters. I need to stay on the index.html page and display the http://localhost:8080/USER-ENTERED-DATA (i.e. /12345) – c12 Oct 16 '17 at 06:28
  • 1
    If you use the same path (`/`) for different actions that you want to handle with different servlets, then you have to build an additional servlet/filter, that analyses the URL and then decides which servlet to call (e.g. by forwarding the request to another path the other (`Retrieve`) servlet is listening to). – Niklas P Oct 16 '17 at 06:56