2

我正在处理一个 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>

我在行出现错误:

       <% if (x.equals("confirm")){ %>

知道为什么吗?

4

2 回答 2

0

首先,停止不必要地打开和关闭 JSP 标记。它的草率和不可读。其次,您缺少分号。第三,您需要检查参数为空的可能性。未提交表单时,该参数为空。

这是不好的:

 <% String x=request.getParameter("submit")%>
 <% if (x.equals("confirm")){ %>

像这样做:

 <%
   String x = request.getParameter("submit");
   if(x!=null && x.equals("confirm"))
   {
     ...

您还可以反转字符串比较。如果对为 null 的变量使用点运算符,则会出现空指针异常。因此,您可以在字符串文字上使用点运算符,从而避免显式检查 null:

 <%
   String x = request.getParameter("submit");
   if("confirm".equals(x))
   {
     ...

同样,一旦您解决了这个问题,您将遇到if (request.getParameter("user")!="". 您需要使用.equals(),因为在 Java for String==中,!=不比较字符串内容,而是比较指针(即内存地址)等价。

于 2014-03-27T20:44:55.743 回答
0

这个问题似乎不太老。所以我可以放心地为这个问题添加答案。

基本上,当您想在同一页面中处理提交的表单数据时,您可以使用以下代码片段:

    <%
    String check_submit_form = request.getParameter("submit");
    if((request.getParameter("btnLogon") == null)?false:true){
            for(int i =0;i<=100;i++){
                 out.println("Congrts Bro . you have done a great job .");
            }
    }
    else{
    %>

   <form name="form_logon" method="POST" action ="logonHome.jsp">
     <input type="submit" value="Click for Finger Verification" name="btnLogon">
  </form>
  <%
   }
  %>

代码是不言自明的。如果您点击提交按钮,那么您可以处理该表单,否则您将被重定向到该表单。希望这可以帮助 。

于 2017-09-14T11:08:56.867 回答