JSP Radio Button Values

2020-04-30 03:23发布

问题:

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

回答1:

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?



回答2:

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.