【问题标题】:How to show a message in the current JSP page after a submit to a servlet? [duplicate]提交到 servlet 后如何在当前 JSP 页面中显示消息? [复制]
【发布时间】:2019-01-16 12:12:41
【问题描述】:

我有一个 Jsp 页面,其中包含 ID 文本字段,该文本字段从用户那里获取输入,并且该输入在 servlet 中读取。我还在 servlet 中验证该输入。如果用户输入了错误的输入,我需要在 Jsp 中的 ID 字段下方提供类似错误输入的文本消息。

这里是servlet代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // TODO Auto-generated method stub
    services2   reporteeservice = new services2();
    services3      jiraservice  = new services3();
    service4            empid   = new service4();
    String id                   = request.getParameter("ManagerId");
    int Number                  = 1;

    PrintWriter out1=response.getWriter();
    String n = ".*[0-9].*";
    String a = ".*[a-z].*";
    String c = ".*[A-Z].*";

    if( id.matches(n) && id.matches(a) || id.matches(c)) 
    {
      out1.println("valid input");
        try {
        //s.getList(id);
        ....
    }
    else
    { 
        out1.println("not a valid input");
    }

但是如果我像上面一样给出 else 部分,它会将我重定向到下一页并在输入错误时打印 not a valid。但是,我希望它显示在 Jsp 中 ID 字段下的同一页面中。

我的 JSP 页面:

<form name = "reportees" method = "GET" action="reportsto">
    <center>
    <h1><font size="20"> Enter the ID to get the Reportees</font></h1>
        <label><font size="+2">ID</font></label>
        <input name="ManagerId" ype="text" style="font-size:16pt"/>
        <input type="submit" value="submit"/>
        <button type="reset" value="Reset">cancel</button>
    </center>
</form>

【问题讨论】:

  • 如果您想在同一个 Jsp 页面中显示无效的文本消息,您不认为您需要某种 HTML 标记吗?它在哪里?而且,您希望从 servlet 以某种方式再次“调用”同一个 Jsp 页面并更新该标记中的无效消息。有办法做到这一点。您需要对此进行一些研究。
  • PrintWriterprintln 写入 servlet 生成的输出(不是 Jsp)。但是,你已经知道了。
  • 如果您想从一个页面(HTML、Jsp 或 servlet)“转到”另一个页面,servlet 和 Jsp 编程中使用了哪些 API?

标签: java jsp servlets


【解决方案1】:

看看这对你有没有帮助。

<script>
function validateForm() {
  var mid = document.getElementById("ManagerId").value;
  // If manager id is empty 
  if(mid===""){
     alert("Please enter valid manager id.");
    return false;
  } 
}
</script>

<form name = "reportees" method = "GET" onsubmit="return validateForm()" action="reportsto">
    <center>
    <h1><font size="20"> Enter the ID to get the Reportees</font></h1>
        <label><font size="+2">ID</font></label>
        <input name="ManagerId" id="ManagerId" ype="text" style="font-size:16pt"/>
        <input type="submit" value="submit"/>
        <button type="reset" value="Reset">cancel</button>
    </center>
</form>

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多