Fetching Value of Form Field Using Java Servlet

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

java servlet

find value using servlet

Servlets

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