我正在处理一个 JSP 文件(不想使用 servlet),我有一个简单的表单、2 个标签、2 个输入和 2 个按钮,我想打印出提交的字符串 相同的 jsp 页面 ,问题是当我尝试新的时,最后提交的值仍然打印在屏幕上,这就是为什么我想到了一个测试来检查在我们移动到显示之前是否单击了提交按钮,我试过这段代码:
<body>
<form method='post'>
<pre>
<label>Username</label> <input type="text" name="user" required/>
<label>Password</label> <input type="password" name="pwd" required />
<br>
<input type="submit" value="confirm" name ="submit" />
<input type="reset" value="clear" />
</pre>
</form>
<br>
// test if the submit button was clicked (check if value of submit is confirm)
<% String x=request.getParameter("submit")%>
<% if (x.equals("confirm")){ %>
<% if (request.getParameter("user")!="" && request.getParameter("pwd")!=""){ %>
<center>
<h4> user is : <% out.write(request.getParameter("user")); %> </h4>
<br>
<h4> password is : <% out.write(request.getParameter("pwd")); %> </h4>
</center>
<% } else { %>
<h4> inputs r empty !! </h4>
<% } %>
<% } %>
</body>
我在第 1 行遇到错误:
<% if (x.equals("confirm")){ %>
知道为什么吗?
最佳答案
首先,停止不必要地打开和关闭 JSP 标记。它草率且不可读。其次,您缺少分号。第三,您需要检查参数是否为空的可能性。表单未提交时,参数为null。
这很糟糕:
<% String x=request.getParameter("submit")%>
<% if (x.equals("confirm")){ %>
这样做:
<%
String x = request.getParameter("submit");
if(x!=null && x.equals("confirm"))
{
...
您还可以反转字符串比较。如果对为空的变量使用点运算符,则会出现空指针异常。因此,您可以在字符串文字上使用点运算符,从而避免显式检查 null:
<%
String x = request.getParameter("submit");
if("confirm".equals(x))
{
...
此外,一旦你解决了这个问题,你将遇到 if (request.getParameter("user")!=""
的问题。你需要使用 .equals()
因为在 Java 中对于 String ==
,!=
不比较字符串内容,而是比较指针(即内存地址)是否等价。
关于jsp - 如何检查是否按下了按钮(在 jsp 文件中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22691711/