Solved

Servlets - Reading the value of a radio button

Posted on 2000-05-15
16
1,284 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
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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 100 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
starter POM and spring-boot-starter,  spring-boot-web 2 54
maven project error 5 55
eclipse shortcuts 9 55
Basic Java Case or If-Else statement... 3 50
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
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:

770 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