Java 在 servlet 中获取 <select> 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21327772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value of <select> in servlet
提问by nightin_gale
I have:
我有:
<select id="isTitles">
<option value="true">enable</option>
<option value="false">disable</option>
</select>
on my index.jsp. And I would like to know what had been chosen:
在我的 index.jsp 上。我想知道选择了什么:
response.getWriter().write( "User chose: " + request.getAttribute( "isTitles" ) );
But I've got "User chose: null"... = (
但我有“用户选择:空”... = (
采纳答案by Weibo Li
Change your HTML code to:
将您的 HTML 代码更改为:
<select id="isTitles" name="isTitles" >
The id
attribute of select tag is mainly for DOM usages, and name
attribute is to specify the key of a form data.
id
select标签的属性主要用于DOM的使用,name
attribute是指定表单数据的key。
And then use request.getParameter("isTitles")
, your will get the right value. getParameter
is for retrieving parameters from form data and URL query string. While getAttribute
is for transfer data through the process chain during the request life cycle.
然后使用request.getParameter("isTitles")
,您将获得正确的值。getParameter
用于从表单数据和 URL 查询字符串中检索参数。WhilegetAttribute
用于在请求生命周期中通过流程链传输数据。
回答by SpringLearner
change this request.getAttribute( "isTitles" )
to request.getParameter("isTitles" )
将此更改request.getAttribute( "isTitles" )
为request.getParameter("isTitles" )
Also there is no name for the select field so you should also give a name to it
选择字段也没有名称,因此您还应该为其命名
<select id="isTitles" name="isTitles">
<option value="true">enable</option>
<option value="false">disable</option>
</select>
response.getWriter().write( "User chose: " + request.getParameter("isTitles" ) );
回答by Lingasamy Sakthivel
Use
用
request.getParameter("isTitles")
and give name attribute for your select box
并为您的选择框提供名称属性
<select id="isTitles" name="isTitles" >
回答by MS-
You need to pass the name of your attribute as name="isTitles"
您需要将您的属性名称作为 name="isTitles"
<select name="isTitles">
</select>
request.getParameter()
understands the name of the parameter
request.getParameter()
了解参数的名称