david.colais
david.colais

Reputation: 619

HTML form submit error to servlet

I have a basic HTML form as shown which submits a post request to a servlet:

And I submit the using the URL : http://localhost:8080/sample/forms.html

But when the request is submitted the context root part gets erased and the url is seen as:

http://localhost:8080/getFormParam

The form used is:

<form  method="post" action="/getFormParam">
<input type="text" name="user" />
<input type="text" name="id"/>
<input type="submit" value="Submit"/>
<input type="reset" value="clear"/>
</form>

The web.xml mapping is

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <servlet>
        <servlet-name>getFormParam</servlet-name>
        <servlet-class>dep.getFormParam</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>getFormParam</servlet-name>
        <url-pattern>/getFormParam</url-pattern>
      </servlet-mapping>
      </web-app>

What is the issue here.

Upvotes: 0

Views: 495

Answers (2)

Saif Asif
Saif Asif

Reputation: 5668

The problem is just the preceding slash "/" in the action parameter

<form method="post" action="/getFormParam">

When you mention a slash in front of a URL, it means that the resource is located at the context root of the tomcat server (not the context root of the application) which in this case is localhost:8080. If you change it to

<form method="post" action="getFormParam">

it will start working like you want. How-ever it is best that you be aware of URL rewriting concept just in case you don't get trapped in this situation again.In order to overcome this situation, there is a tag inside the JSTL library with the name of url that makes sure that any URL you pass it, it will always resolve to the context root of the application (Url Re-writing).

More detail can be found here

Upvotes: 1

SKR
SKR

Reputation: 813

The problem is in

<form  method="post" action="/getFormParam">

Change it to (Remove / )

<form  method="post" action="getFormParam">

The Post URL will become http://localhost:8080/sample/getFormParam The servlet will get the request now.

Upvotes: 1

Related Questions