Solved

Servlets - Reading the value of a radio button

Posted on 2000-05-15
16
1,168 Views
Last Modified: 2013-11-24
I am really new to servlet. I am writing an online Quiz application using servlets. The questions and answers are picked up from the backend database and displayed in the HTML form using text and radio buttons. For each question there are 4 answers in th eform of radio buttons.
    I would like to know how I can get the values of the radio buttons that the user has checked? I used getParameter("Radio Button Name")...but it returns a null value. Can anyone please help me with this. Some code sample would be helpful.  
0
Comment
Question by:netgeek
  • 6
  • 5
  • 2
  • +3
16 Comments
 

Author Comment

by:netgeek
Comment Utility
Adjusted points from 50 to 75
0
 

Author Comment

by:netgeek
Comment Utility
The HTML form has a set of 10 Question and Answer pairs. So I should be able to read responses to all the ten sets.
0
 
LVL 5

Expert Comment

by:sgoms
Comment Utility
HTML Page:
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>JBuilder Project test.jpr</TITLE>
</HEAD>
<BODY>
<FORM NAME=Main METHOD=POST ACTION="http://localhost:8081/servlet/testServlet">
<H3>Quesion 1</H3>
<INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 1'>Choice 1
<INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 2'>Choice 2
<INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 3'>Choice 3
<H3>Quesion 2</H3>
<INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 1'>Choice 1
<INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 2'>Choice 2
<INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 3'>Choice 3
<H3>Quesion 3</H3>
<INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 1'>Choice 1
<INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 2'>Choice 2
<INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 3'>Choice 3
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>
</BODY>
</HTML>


/**testServlet.java**/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class testServlet extends HttpServlet {

  //Initialize global variables
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }
  //Process the HTTP Get request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = new PrintWriter (response.getOutputStream());
    response.setContentType("text/html");
    out.println("<FONT COLOR=GREEN>");
    out.println("The servlet has received a GET. This is the reply.<br>");
    int i=1;
    while(request.getParameter("Answer"+i) != null){
      out.println("The answer selected for question "+i+" is .."+request.getParameter("Answer"+i)+"<br>");
      i++;
    }
    out.println("</FONT>");
    out.close();
  }
}


The value of the radio button has to be set. my guess is you might not have set the value of the radio button.

chk this out,
-sgoms
0
 

Expert Comment

by:yoavdo
Comment Utility
i would like to add to sqoms, u must add the checked atribute to one of the radio buttons other wise your code will stop on un checked question. or u should go over all answers in a for loop.
0
 

Author Comment

by:netgeek
Comment Utility
Adjusted points from 75 to 100
0
 

Author Comment

by:netgeek
Comment Utility
Actually I have the HTML included in the servlet code. Its a dynamic form generation. Here is the code that I am using:
if ((row1 = result1.FetchRow()) != null && (row2 = result2.FetchRow()) != null && (row3 = result3.FetchRow()) != null && (row4 = result4.FetchRow()) != null && (row5 = result5.FetchRow()) != null)
            {
            for(i=0; i < row1.length; i++)
            for(j=0; j < row2.length; j++)
            for(k=0; k < row3.length; k++)
            for(l=0; l < row4.length; l++)
            for(m=0; m < row5.length; m++)
            toClient.println("<font size=3 color=navy>" + row1[i] + "<BR><BR><INPUT TYPE=RADIO NAME=" + a[inc] + " VALUE=" + row2[j] + " checked >" + row2[j] + "<BR><INPUT TYPE=RADIO NAME=" + a[inc] + " VALUE=" + row3[k] + ">" + row3[k] + "<BR><INPUT TYPE=RADIO NAME=" + a[inc] + " VALUE=" + row4[l] + ">" + row4[l] + "<BR><INPUT TYPE=RADIO NAME=" + a[inc] + " VALUE=" + row5[m] + ">" + row5[m] +"</font><br><br>");
            String value = req.getParameter("a[inc]");
            toClient.println(value); /**********Prints a null value when run**************/
            inc++;
            }


    And its showing NULL for the value that I am priniting.
0
 

Expert Comment

by:rmakharia
Comment Utility
You shuld use the getParameterNames, which returns an enumeration of string. Using these string (i.e. name objects), get their values using getParameterValues. Check for the desired value and use it in your program.
0
 

Author Comment

by:netgeek
Comment Utility
Can you please elaborate on it. I am not familiar with enumeration types. Some sample code would really help me. Thank you.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Expert Comment

by:sgoms
Comment Utility
It should be,
String value = req.getParameter(a[inc]);

not a[inc] within quotes.

0
 
LVL 5

Accepted Solution

by:
sgoms earned 100 total points
Comment Utility
Have a servlet generate the dynamic html and another servlet take care of processing it.

Example:
/**testServlet.java**/

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class testServlet extends HttpServlet {

  //Initialize global variables
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }
  //Process the HTTP Get request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = new PrintWriter (response.getOutputStream());
    response.setContentType("text/html");
    out.println("<FONT COLOR=GREEN>");
    out.println("The servlet displays a quiz<br>");
    out.println("<BODY>");
    out.println("<FORM NAME=Main METHOD=POST ACTION='http://localhost:8081/servlet/ProcessDataServlet'>");
    for(int i=1;i<=3;i++){
    out.println("<H3>Quesion"+i+"</H3>");
    out.println("<INPUT TYPE=RADIO NAME=Answer"+i+" VALUE='Choice 1'>Choice 1");
    out.println("<INPUT TYPE=RADIO NAME=Answer"+i+" VALUE='Choice 2'>Choice 2");
    out.println("<INPUT TYPE=RADIO NAME=Answer"+i+" VALUE='Choice 3'>Choice 3");
    }
    out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");
    out.println("</FORM></BODY></HTML>");
    out.println("</FONT>");
    out.close();
  }
}

/**ProcessDataServlet.java**/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class ProcessDataServlet extends HttpServlet {

  //Initialize global variables
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }
  //Process the HTTP Get request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = new PrintWriter (response.getOutputStream());
    response.setContentType("text/html");
    out.println("<FONT COLOR=BLUE>");
    out.println("The servlet displays the selected answers<br>");
    int i=1;
    while(request.getParameter("Answer"+i) != null){
      out.println("Answer to question "+i+" is "+request.getParameter("Answer"+i));
      out.println("<br>");
      i++;
    }
    out.println("</FONT>");
    out.close();
  }
}

all the best,
-sgoms
0
 

Expert Comment

by:smithan
Comment Utility
What if the generation of the radio buttons itself is dynamic inside the servlet?

say:
out.println("<INPUT TYPE=RADIO NAME=" + a[inc] +
                           "VALUE=" + row[i] + "checked>" + row[i] );
where:
a[inc] is the radiobutton name and row[i] is the choice from the database.

i.e; if we display the choices from the database then how do i print the value of the checked radio button.

is it just :
String value = request.getParameter(a[inc]); out.println(value);
if so:                it still gives null

Please help!:-(!


0
 

Expert Comment

by:yoavdo
Comment Utility
have u watched the source code of the html file generated by the servlet?
check if the a[inc] name is realy the one u want it to be. can u send the servlet code and the generated html to :
sdobrin@t2.technion.ac.il ?

it it hard to read your sources here.
I'm sure i could help u !
0
 

Expert Comment

by:anilbathula
Comment Utility
HTML Page:
                   <HTML>
                   <HEAD>
                   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
                   <TITLE>JBuilder Project test.jpr</TITLE>
                   </HEAD>
                   <BODY>
                   <FORM NAME=Main METHOD=POST ACTION="http://localhost:8081/servlet/testServlet">
                   <H3>Quesion 1</H3>
                   <INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 1'>Choice 1
                   <INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 2'>Choice 2
                   <INPUT TYPE=RADIO NAME=Answer1 VALUE='Choice 3'>Choice 3
                   <H3>Quesion 2</H3>
                   <INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 1'>Choice 1
                   <INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 2'>Choice 2
                   <INPUT TYPE=RADIO NAME=Answer2 VALUE='Choice 3'>Choice 3
                   <H3>Quesion 3</H3>
                   <INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 1'>Choice 1
                   <INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 2'>Choice 2
                   <INPUT TYPE=RADIO NAME=Answer3 VALUE='Choice 3'>Choice 3
                   <INPUT TYPE=SUBMIT VALUE=Submit>
                   </FORM>
                   </BODY>
                   </HTML>


                   /**testServlet.java**/
                   import javax.servlet.*;
                   import javax.servlet.http.*;
                   import java.io.*;
                   import java.util.*;

                   public class testServlet extends HttpServlet {

                     //Initialize global variables
                     public void init(ServletConfig config) throws ServletException {
                       super.init(config);
                     }

                       public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                   IOException {
                          doPost(request,response);
                       }
                     //Process the HTTP Get request
                     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                   IOException {
                       PrintWriter out = new PrintWriter (response.getOutputStream());
                       response.setContentType("text/html");
                       out.println("<FONT COLOR=GREEN>");
                       out.println("The servlet has received a GET. This is the reply.<br>");
                       int i=1;
                       while(request.getParameter("Answer"+i) != null){
                         out.println("The answer selected for question "+i+" is .."+request.getParameter("Answer"+i)+"<br>");
                         i++;
                       }
                       out.println("</FONT>");
                       out.close();
                     }
                   }

This code is working fine i tested with Netscape and IE4.
0
 

Author Comment

by:netgeek
Comment Utility
Thanks for your valuable suggestions. It works great.
0
 
LVL 5

Expert Comment

by:sgoms
Comment Utility
anilbathula, i guess i have posted the code above!!
0
 
LVL 5

Expert Comment

by:sgoms
Comment Utility
glad that it worked!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
nestparen challenge 4 55
computer science syllabus 3 52
maven java path setting 5 49
Python Assistance 7 30
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now