我在index.html中有这个表单
<form action="Servlet">
<p>Type text:<br><textarea cols="100" rows="10" name=encipher></textarea></p>
<input type="submit" value="Encipher" name=encipherSubmit id="a"/>
<input type="submit" value="Decipher" name=decipherSubmit id="b"/>
</form>
而且我不知道如何从按钮中获取识别器。我需要在按下第一个按钮时执行加密方法,在第二个按钮按下时执行解密方法。 对于Servlet.java中的textarea,我有代码:
String encipher = req.getParameter("encipher");
如何从按钮中获取参数?
答案 0 :(得分:1)
每个输入都是使用您提供的名称发送的。您的提交按钮有名称。因此,如果单击“加密”按钮,则会有一个名为encipherSubmit
的参数,其值为Encipher
。如果您点击“解密”按钮,则会有一个名为decipherSubmit
的参数,其值为Decipher
。
就好像这些是文本字段一样,但好处是只发送实际用于提交的按钮。
所以你可以这样做:
String encipherButton = req.getParameter("encipherSubmit");
String decipherButton = req.getParameter("decipherSubmit");
if ( encipherButton != null && encipherButton.equals("Encipher") ) {
// Do encipher operation
} else if ( decipherButton != null && decipherButton.equals("Decipher") ) {
// Do decipher operation
} else {
// Form was submitted without using the buttons.
// Decide what you want to do in this case.
}
事实上,在大多数情况下,只需检查encipherButton != null
和decipherButton != null
即可。
答案 1 :(得分:-2)
嗯,你不知道用这种方式点击哪个按钮,因为按钮只是表单提交。实际上,servlet可以处理您通过HTTP发送的任何标头或数据,但不发送按钮名称。
或者,您可以为每个按钮编写一个javascript onclick事件处理程序,然后使用其他参数以编程方式发送提交 - 单击该按钮。