?
Solved

Servlets - Reading the value of a radio button

Posted on 2000-05-15
16
Medium Priority
?
1,580 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +3
16 Comments
 

Author Comment

by:netgeek
ID: 2812197
Adjusted points from 50 to 75
0
 

Author Comment

by:netgeek
ID: 2812198
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
ID: 2812409
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
Create CentOS 7 Newton Packstack Running Keystone

A bug was filed against RDO for the installation of Keystone v3. This guide is designed to walk you through the configuration for using Keystone v3 with Packstack. You will accomplish this using various repos and the Answers file.

 

Expert Comment

by:yoavdo
ID: 2813184
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
ID: 2814022
Adjusted points from 75 to 100
0
 

Author Comment

by:netgeek
ID: 2814023
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
ID: 2814073
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
ID: 2814247
Can you please elaborate on it. I am not familiar with enumeration types. Some sample code would really help me. Thank you.
0
 
LVL 5

Expert Comment

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

not a[inc] within quotes.

0
 
LVL 5

Accepted Solution

by:
sgoms earned 400 total points
ID: 2815123
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
ID: 2815281
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
ID: 2815873
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
ID: 2816006
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
ID: 2817982
Thanks for your valuable suggestions. It works great.
0
 
LVL 5

Expert Comment

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

Expert Comment

by:sgoms
ID: 2817989
glad that it worked!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

765 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