Introduction

A servlet can fetch the value of a form field using the getParameter() method of the servlet request. The HTML form can submit a value of the form fields by using a URL pattern of the servlet into the action attribute of the form tag. If the method attribute contains Get as its value and destination servlet is a sub-class of the Http servlet then doGet() method gets invoked. If the method attribute contains post as its value and destination servlet is a sub-class of http servlet then doPost() method of the servlet gets invoked. If the destination servlet is a sub-class of Generic servlet then the service() method gets invoked without depending upon the value of method attribute. The getParameter() method of request accepts the name of the form field as its arguments and returns value of the form fields as a string. If the specified form field does not exist in the request then the getParameter() method returns Null. If the form exists in a servlet and it requires submission of the form into the current servlet then the action attribute does not need to be used in the form tag.

Example

A servlet to receive two numbers and display the addition.
  1. import javax.servlet.*;
  2. import javax.servlet.http.*;
  3. import java.io.*;
  4. public class number extends HttpServlet
  5. {
  6. public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
  7. {
  8. String s1=req.getParameter("t1");
  9. String s2=req.getParameter("t2");
  10. PrintWriter out=res.getWriter();
  11. out.println("<html><body>");
  12. if(s1 ==null)
  13. {
  14. out.println("<form>");
  15. out.println("<h1>Enter No1<input type='text' name='t1'></h1>");
  16. out.println("<input type='submit' value='submit'>");
  17. out.println("</form>");
  18. }
  19. else if(s2 ==null)
  20. {
  21. out.println("<form>");
  22. out.println("<h1>Enter No2<input type='text' name='t2'></h1>");
  23. out.println("<input type='hidden' name='t1' value='"+s1+"'>");
  24. out.println("<input type='submit' value='submit'>");
  25. out.println("<form>");
  26. }
  27. else
  28. {
  29. int x=Integer.parseInt(s1);
  30. int y=Integer.parseInt(s2);
  31. out.println("<h1>Result is "+(x+y)+"</h1>");
  32. }
  33. out.println("</body></html>");
  34. }
  35. }

Storing and Compiling

Store the file inside the class folder of the context (E:\Servlet\WEB-INF\classes).

Compile the file as below:

javac -cp servlet-api.jar number.java (for tomcat 6.0)

Servlet in java

Setting in web.xml file

Note: - Note the Highlighted or bold portion in the below web.xml file, to be added.
  1. <?xml version="1.0" encoding="ISO-8859-1" ?>
  2. - <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. --> <!-- Inject Script Filtered -->
  16. --<web-appxmlnsweb-appxmlns=http://java.sun.com/xml/ns/javaee
  17. xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
  18. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  19. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  20. <servlet>
  21. <servlet-name>number</servlet-name>
  22. <servlet-class>number</servlet-class>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>number</servlet-name>
  26. <url-pattern>/number</url-pattern>
  27. </servlet-mapping>
  28. </web-app>

Running it in web browser


First start the Apache Tomcat 6.0, which is a web server. Then type the below URL.

http://localhost:8082/x/number

Here x is the context path location, which we have to give in the server.xml file, which is present inside the Tomcat installation directory (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf)

Server.xml settings

Note: - In the below server.xml file we have to specify the context path as below.

<Context path="/x" docBase="E:\Servlet" reloadable="true" debug="0" />

server.xml file
  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <!-- Note: A "Server" is not itself a "Container", so you may not
  17. define subcomponents such as "Valves" at this level.
  18. Documentation at /docs/config/server.html
  19. -->
  20. <Server port="8005" shutdown="SHUTDOWN">
  21. <!--APR library loader. Documentation at /docs/apr.html -->
  22. <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  23. <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  24. <Listener className="org.apache.catalina.core.JasperListener" />
  25. <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  26. <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  27. <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  28. <!-- Global JNDI resources
  29. Documentation at /docs/jndi-resources-howto.html
  30. -->
  31. <GlobalNamingResources>
  32. <!-- Editable user database that can also be used by
  33. UserDatabaseRealm to authenticate users
  34. -->
  35. <Resource name="UserDatabase" auth="Container"
  36. type="org.apache.catalina.UserDatabase"
  37. description="User database that can be updated and saved"
  38. factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
  39. pathname="conf/tomcat-users.xml" />
  40. </GlobalNamingResources>
  41. <!-- A "Service" is a collection of one or more "Connectors" that share
  42. a single "Container" Note: A "Service" is not itself a "Container",
  43. so you may not define subcomponents such as "Valves" at this level.
  44. Documentation at /docs/config/service.html
  45. -->
  46. <Service name="Catalina">
  47. <!--The connectors can use a shared executor, you can define one or more named thread pools-->
  48. <!--
  49. <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
  50. maxThreads="150" minSpareThreads="4"/>
  51. -->
  52. <!-- A "Connector" represents an endpoint by which requests are received
  53. and responses are returned. Documentation at :
  54. Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
  55. Java AJP Connector: /docs/config/ajp.html
  56. APR (HTTP/AJP) Connector: /docs/apr.html
  57. Define a non-SSL HTTP/1.1 Connector on port 8080
  58. -->
  59. <Connector port="8082" protocol="HTTP/1.1"
  60. connectionTimeout="20000"
  61. redirectPort="8443" />
  62. <!-- A "Connector" using the shared thread pool-->
  63. <!--
  64. <Connector executor="tomcatThreadPool"
  65. port="8080" protocol="HTTP/1.1"
  66. connectionTimeout="20000"
  67. redirectPort="8443" />
  68. -->
  69. <!-- Define a SSL HTTP/1.1 Connector on port 8443
  70. This connector uses the JSSE configuration, when using APR, the
  71. connector should be using the OpenSSL style configuration
  72. described in the APR documentation -->
  73. <!--
  74. <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
  75. maxThreads="150" scheme="https" secure="true"
  76. clientAuth="false" sslProtocol="TLS" />
  77. -->
  78. <!-- Define an AJP 1.3 Connector on port 8009 -->
  79. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
  80. <!-- An Engine represents the entry point (within Catalina) that processes
  81. every request. The Engine implementation for Tomcat stand alone
  82. analyzes the HTTP headers included with the request, and passes them
  83. on to the appropriate Host (virtual host).
  84. Documentation at /docs/config/engine.html -->
  85. <!-- You should set jvmRoute to support load-balancing via AJP ie :
  86. <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
  87. -->
  88. <Engine name="Catalina" defaultHost="localhost">
  89. <!--For clustering, please take a look at documentation at:
  90. /docs/cluster-howto.html (simple how to)
  91. /docs/config/cluster.html (reference documentation) -->
  92. <!--
  93. <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
  94. -->
  95. <!-- The request dumper valve dumps useful debugging information about
  96. the request and response data received and sent by Tomcat.
  97. Documentation at: /docs/config/valve.html -->
  98. <!--
  99. <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
  100. -->
  101. <!-- This Realm uses the UserDatabase configured in the global JNDI
  102. resources under the key "UserDatabase". Any edits
  103. that are performed against this UserDatabase are immediately
  104. available for use by the Realm. -->
  105. <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
  106. resourceName="UserDatabase"/>
  107. <!-- Define the default virtual host
  108. Note: XML Schema validation will not work with Xerces 2.2.
  109. -->
  110. <Host name="localhost" appBase="webapps"
  111. unpackWARs="true" autoDeploy="true"
  112. xmlValidation="false" xmlNamespaceAware="false">
  113. <!-- SingleSignOn valve, share authentication between web applications
  114. Documentation at: /docs/config/valve.html -->
  115. <!--
  116. <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
  117. -->
  118. <!-- Access log processes all example.
  119. Documentation at: /docs/config/valve.html -->
  120. <!--
  121. <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
  122. prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
  123. -->
  124. <Context path="/x" docBase="E:\Servlet" reloadable="true" debug="0" />
  125. </Host>
  126. </Engine>
  127. </Service>
  128. </Server>
Output

java servlet

find value using servlet

Servlets

Thanks for reading and please be kind enough to give the feedback.