Getting checkbox values from HTML form in Servlet

8 May 2012 By Nithya Vasudevan 10,367 views 10 Comments
GD Star Rating
loading...

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Apache Tomcat 6.x
  • Java EE 5 API (Servlet 2.5)
  • [Optional] For monitoring and analyzing HTTP headers between the browser and web servers, you can use one of these add-ons of Firefox
    • Live HTTP Headers
    • HttpFox

Setting up development environment

If you are new to developing Servlet with Tomcat and Eclipse, you can read this page before proceeding with this example.

Sending multiple values for single parameter

  • If the same parameter name appears in the form data more than once, we use getParameterValues (which returns an array of strings) instead of getParameter (which returns a single string corresponding to the first occurrence of the parameter).
    • The <input type=”checkbox”> and <select> allows user to select more than one option.
  • The return value of getParameterValues() is null for nonexistent parameter names or none of the choices are selected.
  • It is a one-element array when the parameter has only a single value.

HTML Form

Servlet Code

Method signature:

String[] getParameterValues(String name)

  • Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
  • For Servlets, parameters are contained in the query string (GET request) or request body (POST request).
  • This method should be used for the parameter which may have more than one value.
  • If the parameter has a single value, the array has a length of 1.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation=
	"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>MultipleValuesSingleParam</servlet-name>
    <servlet-class>
	com.ibc.multiplevalues.MultipleValuesSingleParamServlet
    </servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MultipleValuesSingleParam</servlet-name>
    <url-pattern>/multiplevalues.do</url-pattern>
  </servlet-mapping>
</web-app>

Project Folder Structure

The complete directory structure of this project is shown below.

Output

Program Control Flow

  • Web client (browser) requests the server/container for the HTML file (multiplevalues.html) through request URL.
  • Container responses with the actual content of HTML file along with HTTP response headers.
  • When the user submits the form, web client sends request to the Servlet along with form data in the body of HTTP header since it is a POST request.
  • Servlet processes the form parameters and responds with the actual HTML content.

The content of HTTP request and response headers can be monitored using browser add-ons such as Live HTTP Headers, HttpFox, etc

Sample HTTP request and response headers using these add-ons is shown below.

HTTP Request

http://localhost:8080/ReqAndResChapter4/multiplevalues.html
GET /ReqAndResChapter4/multiplevalues.html HTTP/1.1
Host: localhost:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
…..
…..

HTTP Response

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
Content-Type: text/html
Content-Length: 816
Content: HTML Form (multiplevalues.html)

HTTP Request


Form parameter in Request body, since it is a POST request.

HTTP Response

To develop and run this example with Tomcat and Eclipse, refer this page.

Getting checkbox values from HTML form in Servlet, 3.9 out of 5 based on 7 ratings

Tags: , , , , , , , , , , ,

10 thoughts on “Getting checkbox values from HTML form in Servlet

  1. can u print the all the other two options(i.e.,Apple,Banana) which are not checked also in the resultant JSP

    GD Star Rating
    loading...
    • You cannot retrieve unchecked values from request object. If you need those values you have to maintain a list or set containing all the items and then compare with the checked items.

      GD Star Rating
      loading...
  2. Do you know how to get the fruits in a database table ? i mean how to insert the fruits column with the multiple values ?

    GD Star Rating
    loading...
    • One way to do this is to convert this String[] to String and the insert it in table as shown below

      String[] favoriteFruits = {"Apple", "Orange", "Grapes", "Pineapple"};
      String result = "";
      for(String s : favoriteFruits) {
      	result += s;
      	result += ",";
      }
      //insert value of 'result' variable in table

      Retrive it as a String from table and tokenize it to get list of fruits as shown below.

      String[] favFruits = result.split(",");
      for(String fruit : favFruits) {
      	System.out.println(fruit);
      }
      GD Star Rating
      loading...
  3. I want to store check box data to a java-bean in string array format.
    I want to display the check box data which is entered ,
    how can i display in JSP.

    GD Star Rating
    loading...

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>