如何阻止JSP页面执行servlet?

时间:2016-11-13 12:12:55

标签: javascript java jsp servlets

我只是想制作一个简单的网络应用程序。它应该接受所有输入,验证它们并将其存储在数据库中或显示错误。我通过外部JavaScript验证我的表单时遇到问题。如果字段为空,则完成所有检查,但JSP将控件定向到Servlet。我需要停止JSP页面的进一步发展。请帮忙!这是代码:

JSP:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
<script type="text/javascript" src="js/validationJS.js"></script>
</head>
<body>

<h1 align="center">Teacher Management System</h1>

<form name="TeacherRegistrationForm" action="TeacherController" method="post" >
<input type="hidden" name="source" value="AddTeacher">
<table>
<tr>
<td>
ID:<input type="text" name="teacherId" />
</td>
</tr>

<tr>
<td>
Name:<input type="text" name="teacherName" />
</td>
</tr>


<tr>
<td>
Address:<textarea type="text" rows="5" name="teacherAddress" ></textarea>
</td>
</tr>


<tr>
<td>
Qualification:<input type="text" name="teacherQualification" />
</td>
</tr>


<tr>
<td>
Years Of Experience:<input type="text" name="teacherExp" />
</td>
</tr>


<tr>
<td>
Age:<input type="text" name="teacherAge" />
</td>
</tr>

<tr>
<td>
<input type="submit" name="teacherAdd" value="ADD" onclick="validate()"/>
<input type="reset" name="teacherReset" value="RESET FIELDS" /><br><br>
<a href="WelcomePage.jsp" style="text-decoration: underline">Go Back</a>
</td>
</tr>


</table>
</form>

</body>
</html>

使用Javascript:

    function validate()
{   
    boolean result=false;
    if(document.TeacherRegistrationForm.teacherId.value=="")
    {

        document.TeacherRegistrationForm.teacherId.value= "Please Enter a valid ID";
        document.TeacherRegistrationForm.teacherId.focus();
        alert("Please enter valid ID");
        result=false;

    }else{result=true;}
    return result;
}

1 个答案:

答案 0 :(得分:-1)

您需要使用<input type="button"

您需要将<input type="submit" name="teacherAdd" value="ADD" onclick="validate()"/>更改为如下所示:

<input type="button" name="teacherAdd" value="ADD" onclick="validate()"/>

<input type="submit"将表单提交给servlet,而不是使用<input type="button"并调用validate()(您正在执行此操作)来验证输入,一旦输入有效,您就可以使用document.myform.submit()提交form

您可以参考以下更新的java脚本validate()方法:

function validate() {   
   if(document.TeacherRegistrationForm.teacherId.value=="") {
      document.TeacherRegistrationForm.teacherId.value= "Please Enter a valid ID";
      document.TeacherRegistrationForm.teacherId.focus();
      alert("Please enter valid ID");
      return;
    } else{
      document.TeacherRegistrationForm.submit();
    }
}