I am very new to java servlet.I am very confused about why we use servlet mapping in web.xml.I have made a project in which I have used two servlets.and if I don't use servlet mapping then also project executes in proper manner..Then why servlet mapping is used..???
Asked
Active
Viewed 221 times
-2
-
How are you defining your servlet? Show some code in the question, so we have a little context. – Andreas Jul 02 '16 at 03:25
-
2Possible duplicate of [Do I really need web.xml for a Servlet based Java web application?](http://stackoverflow.com/questions/30259153/do-i-really-need-web-xml-for-a-servlet-based-java-web-application) – nlloyd Jul 02 '16 at 03:26
-
I have two servlets.one for login and one for logout.And I have not edited web.xml file.then also program executes in proper manner.then why we use servlet mapping? – kushagra Jul 02 '16 at 03:29
-
*How are you defining your servlets?* With `web.xml` or with @annotations. *Show us!* – Andreas Jul 02 '16 at 03:32
1 Answers
0
Servlets should be registered with servlet container.For that, you should add entries in web deployment descriptor web.xml
.It is located in WEB-INF
directory of the web application. you have two option Either you annotation based Servlet where XMl is Not Required and once without Annotation where web.xml is required with Servlet Mapping . the mapping is defined on web.xml like
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/HelloWorld.do</url-pattern>
</servlet-mapping>
- Suppose on Submit any form data you want to call HelloWorld Servlet then for that servlet we have configure one unique URl that is defined as
/HelloWorld.do
so when you Submit the form data it will load prepspective Servlet But URL should be shown like/HelloWorld.do
- if you want to call HelloServlet from form Data then from Client code/Front end code call
action ="/HelloWorld.do"
full tag is<form action="action=/HelloWorld.do" method="post">
- you can call Servlet by creating servlet object as well. but suppose if you are lots of servlet file is there then unique URl pattern is required that is convient for programmer .
- Once you do login on form action call login action servlet URL and while log out call logout servlet URL .
Happy to help

Anand Dwivedi
- 1,452
- 13
- 23
-
Sir,but url pattern are auto-generated.Then why we should explicitly provide unique url for different servlets? – kushagra Jul 02 '16 at 04:15
-
kushagra - meanse you are using @annotation based servlet so for that XML mapping is not required . as i mention on my post . Happy to help – Anand Dwivedi Jul 02 '16 at 06:09