2

I was wondering how to get radio button values. So suppose, I have a form that has two radio buttons. I would like to get the value associated with the button. However, I get null when I try to.

Form portion

<form method="post" action="insert.jsp" enctype=text/plain>
<table>
<INPUT TYPE="radio" name="command" value="0">Run<INPUT TYPE="radio" NAME="command" VALUE="1">Walk<BR>

Insert.jsp portion

String sCommand=(String)request.getParameter("command");
out.println(sCommand);

So in turn, it prints out null

Jonas
  • 121,568
  • 97
  • 310
  • 388
user1709294
  • 1,675
  • 5
  • 18
  • 21

2 Answers2

4

Use GET method instead of POST and your code will run. (if you want to use 'text/plain') and also see the answer given by @divyabharathi for the correct enctype for POST method.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="insert.jsp" enctype=text/plain>
<INPUT TYPE="radio" name="command" value="0"/>Run
<INPUT TYPE="radio" NAME="command" VALUE="1"/>Walk
<INPUT TYPE="submit" VALUE="submit" />
</form>
<%
String sCommand = request.getParameter("command");
out.println(sCommand);
%>
</body>
</html>

but I strongly recommend you to not use scriplets in your JSP, have a look at How to avoid Java Code in JSP-Files?

Community
  • 1
  • 1
Bhushan
  • 6,151
  • 13
  • 58
  • 91
1

The null value returned by the request.getParameter("command") is due to the fact that you are using enctype="plain/text" in your jsp.

The default encoding for an HTTP post request (what your servlet is expecting) is application/x-www-form-urlencoded; not text/plain.

divyabharathi
  • 2,187
  • 17
  • 12
  • @divyabharathi OP has not mentioned anywhere that he is using `enctype="multipart/form-data`, OP is using `enctype=text/plain` – Bhushan Apr 03 '13 at 05:51
  • @Bhushan May be her intention is to use that one,instead of text/plain – Suresh Atta Apr 03 '13 at 06:00
  • @Baadshah using `multipart/form-data` will not solve the problem, but surely it will complicate it more, because looking at the code there is no need to use `multipart/form-data` – Bhushan Apr 03 '13 at 06:02
  • @Baadshah yes I know that, I was just pointing it, now this answer will work – Bhushan Apr 03 '13 at 06:07