• Post Reply Bookmark Topic Watch Topic
  • New Topic

JSP to read name and gender from an HTML form and provide feedback  RSS feed

 
Betty Christiansen
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a class assignment I have to write a JSP program that will get the name and gender from a simple HTML form and then provide feedback to the user such as "Enter your name" if they leave that field blank. The HTML form has a textField for the name and two radio buttons for male and female, plus a submit button. We covered JSPs only briefly so along with being a Java newbie, JSPs are pretty foreign. I had written the same program as a servlet so I attempted using the similar code for the JSP. I'm using switch to get the gender from the radio buttons but that doesn't seem to work as I keep getting the response "Please select your gender". Could someone spot where I might have taken a wrong turn here?

My JSP code (please be gentle):

 
Paul Ngom
Ranch Hand
Posts: 355
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

try {
radio = Integer.parseInt(request.getParameter("rd"));
} catch (Exception e) {
errors.add("<h1>Please select your gender.<h1>");
}


Please, add out.println("rd="+gender) to display gender value. You might be trying to convert a String to an Integer which is why the Exception is executed. Please, paste the content of the first page that is sending the parameters
 
Betty Christiansen
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the HTML code:

 
Paul Ngom
Ranch Hand
Posts: 355
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

int radio = -1;
try {
radio = Integer.parseInt(request.getParameter("rd"));
} catch (Exception e) {
errors.add("<h1>Please select your gender.<h1>");
}
switch (radio) {
case 0:
gender = "Mr";
break;
case 1:
gender = "Ms";
break;

}


I don't see the need of this code. The variable gender has the required value already when you assign it as below

String name = request.getParameter("name");
String gender = request.getParameter("rd");


The variable name also get the required value. So you don't need to call another request.getParameter("name") as you did below. Just print the variable name;

out.println("<h1>Thank you " + gender + ". "
+ request.getParameter("name") + "<h1>");


out.println("<h1>Thank you " + gender + ". "
+ name + "<h1>");
 
Betty Christiansen
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always try to make things harder than they are. Thank you, that works perfectly!!

New JSP code:

 
Paul Ngom
Ranch Hand
Posts: 355
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Betty
All is well.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!