URL mapping issue

I have .war file named notebook.war . I’m deploying it using tomcat, putting it to the webapps directory and then starting tomcat.

There is a form with button

<form id="jform" method="post" action="/add">

and there is a servlet, mapped in web.xml

<servlet>
    <servlet-name>Create</servlet-name>
    <servlet-class>controller.CreateServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Create</servlet-name>
    <url-pattern>/add</url-pattern>
</servlet-mapping>

I launch tomcat, write localhost:8080/notebook in browser and go to the main page, then I go to the page http://localhost:8080/notebook/add.html through the link on the main page. Page http://localhost:8080/notebook/add.html contains that form and after submiting it I go to the http://localhost:8080/add instead of http://localhost:8080/notebook/add.

And even after I have remapped /add to /notebook/add in servlet mapping and form action tag, I go to the http://localhost:8080/add after submiting form.

How to make http://localhost:8080/notebook/add instead of http://localhost:8080/add?

Answer

You need to define your <form> as

<form id="jform" method="post" action="add">

Notice, how the action attribute doesn’t have a leading / which is what making your client go to the website’s root directory i.e. localhost:8080/ and then add.

When you specify the action as add, it gets interpreted relatively to the current URL’s context root i.e. /notebook and hence makes the client post to /notebook/add.

Leave a Reply

Your email address will not be published. Required fields are marked *