提交到servlet后如何在当前JSP页面中显示消息?

时间:2019-01-16 12:12:42

标签: java jsp servlets

我有一个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 部分,则会在输入错误时将我重定向到下一页并打印无效。但是,我希望将其显示在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>

1 个答案:

答案 0 :(得分:0)

看看这是否对您有帮助。

<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>