StrugglingCoder
StrugglingCoder

Reputation: 5011

How to map a servlet call from a JSP page using form action?

I have a JSP page named Welcome_2.html HTML page directoryand in its form action I have invoked a servlet like this :

<form action="/servlets/MyFirstServlet" method="post" id="form_id">

The servlet "MyFirstServlet" is under servlet directory WEB-INF classes servlets MyFirstServlet

and the jsp is under the folder HTML which is in the same level like WEB-INF

i.e. inside practice I have 3 foldersproject structure HTML META-INF WEB-INF

in web.xml I have the following snippet

    <servlet>
    <servlet-name>MyFirstServlet</servlet-name>
    <servlet-class>servlets.MyFirstServlet</servlet-class>
</servlet>  
<servlet-mapping>
    <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/servlets/MyFirstServlet</url-pattern>
</servlet-mapping>

Why the servlet is not being invoked? I am clicking on the HTML page on my browser and trying to invoke the servlet ... I am just a beginner pardon me for my poor intellect.

Upvotes: 1

Views: 18504

Answers (4)

James
James

Reputation: 95

If you use tomcat 7 , you don't need to care about that. For example :

In your servlet :

@WebServlet("/myFirstServlet")  

public class LoginPage extends HttpServlet {

   // your code 

}

In your html :

<!-- here you write myFirstServlet in the action tag -->
<form id="somethingGoesHere" action="myFirstServlet" method="post" >

Upvotes: 2

Maurice Perry
Maurice Perry

Reputation: 32831

Unless your app is deployed as ROOT.war, all your URLs will be relative to http://myserver/webapp. So my guess is that you should rather use relative URLs. As your JSP is in HTML, you would need to write:

<form action="../servlets/MyFirstServlet" method="post" id="form_id">

Upvotes: 1

Santhosh
Santhosh

Reputation: 8187

Change your jsp form to ,

<form action="/servlets/MyFirstServlet" method="post" id="form_id">

to match the url pattern in your web.xml

<servlet-mapping>
    <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/servlets/MyFirstServlet</url-pattern>
</servlet-mapping>

This line <url-pattern>/servlets/MyFirstServlet</url-pattern> refers that url's matching the pattern will invoke the MyFirstServlet

Read the Oracle Tutorial before you configure your web.xml elements

Hope this helps !!

Upvotes: 7

SpringLearner
SpringLearner

Reputation: 13844

As your form action is "/servlets/First" so your url pattern should be

<url-pattern>/servlets/First</url-pattern>

Upvotes: 1

Related Questions