Solved

Servlets - Reading the value of a radio button

Posted on 2000-05-15
16
1,217 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Problem to start Neon 20 82
JUnit 4 @Before and @BeforeClass differences 3 47
custom annotations 9 27
Error trying to install RTMT Win7 5 38
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
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 the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

948 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

18 Experts available now in Live!

Get 1:1 Help Now