检查按下了哪个提交按钮时的空值

时间:2014-04-16 21:39:41

标签: html forms jsp

我现在已经尝试了两个小时,但仍然没有得到结果。我在“test.jsp”文件中有一些像这样的html

<input type ="submit" name="watch" value="Edit" id="edit"></input>

<input type ="submit" name="case" value="Edit" id="editt"></input>

然后我有一个表单,当按下上面的任何一个按钮弹出时使用jquery

<form action="servlet.jsp" method="post">
<fieldset>
  <label for="Name">Name</label>
  <input type="text" name="name" id="name" value=""><br>
  <label for="Price">Price</label>
  <input type="text" name="Price" id="price" value=""><br>
</fieldset>
</form>  

我的JSP由

组成
<% String param = request.getParameter("watch"); %>
<% String param2 = request.getParameter("case"); %>

所以基本上我有两个编辑按钮,取决于按下哪个编辑按钮,它应该预先填充表格值。现在我的表单值为“”,因为无论我按什么按钮,我的getParameter总是为空。

我已经尝试了以下代码,检查值是否为NULL,然后执行某些操作,如果它们不是等,但无论按钮都返回null

if(param !=null){
    //assign variables and populate with data x
}
//and so on

所以我的问题是,首先,我正确地“获取”参数。其次,如果是这样,任何想法为什么我将这两个参数都设为null,无论我按哪个提交按钮。

2 个答案:

答案 0 :(得分:1)

首先,输入是一个自闭标签。这意味着您使用空格后跟/>而不是</input>

来关闭它
<input type="submit" name="watch" value="Edit" id="edit" />
<input type="submit" name="case"  value="Edit" id="editt" />

这可能就是问题所在。在更改后,您的代码可能会很好地工作。但是我会注意到将两个按钮命名为同一个东西并给它们不同的值会更容易,因为你只需要读取一个按钮并切换值:

<input type="submit" name="submit"  value="Edit X" id="edit" />
<input type="submit" name="submit"  value="Edit Y" id="editt" />

然后在servlet或其他JSP中:

String button = request.getParameter("submit");
if(button == null)
{
  out.print("no form was submitted");
  return;
}
else if("Edit X".equals(button))
{
  out.print("button 1 was pressed");
  return;
}
else if("Edit Y".equals(button))
{
  out.print("button 2 was pressed");
  return;
}

答案 1 :(得分:0)

您的JSP应该是:

<% String param = request.getParameter("edit"); %>
<% String param2 = request.getParameter("editt"); %>
相关问题