【问题标题】:How to make the form to re-appear again?如何让表格重新出现?
【发布时间】:2013-04-01 03:42:41
【问题描述】:

我正在寻找如果表单包含空值,那么表单需要再次出现在用户面前,要求填写信息。此检查必须在 servlet 中完成。 我正在尝试使用以下代码,但是当我单击提交按钮时,它仍然不会再次出现。

String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
if(request.getParameter("firstname").equals(" ") || request.getParameter("lastname").equals(""))
{
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
}

我还缺少什么吗?有人可以解释一下吗?

【问题讨论】:

  • 请在此处发布您的 servlet 的完整上下文

标签: jsp jakarta-ee servlets


【解决方案1】:
  1. 在获得参数时始终检查空值。
  2. 即使您正在测试垃圾代码,也要避免重复代码(使其成为 练习,编码技巧)例如使用 request.getParameter("名字");有条件的时候已经 分配给一个字符串变量。
  3. 避免不必要的代码。例如,代码中的“return”语句

如果处理不当,可能会遇到 NPE 空指针异常。

    String firstname = request.getParameter("firstname"); // check other condiftions as well
    if(firstname==null || "".equals(firstname) || " ".equals(firstname)){
    /* your code
    use below line to redirect to any page 
    make sure you are providing correct path of index.jsp or any servlet for redirection
    servlet mapping should be defined in web.xml*/

response.sendRedirect("index.jsp"); 
    }

【讨论】:

    【解决方案2】:

    正如大家所说,请清理您的代码。在servlet 中就这样做。

       if(request.getParameter("firstname") ==null){//and other conditions here
           response.sendRedirect("/index.jsp");        
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多