JavaScript验证表单数据,并提交给Java后台

时间:2021-05-19 05:50:22

jsp页面新建表单:

说明:action路径需要修改成你自己的


<form  id="signForm" action="doSignIn">

        <input type="email" id="email"  placeholder="Email address" name="email" value="" required autofocus>

        <input type="password" id="password1" placeholder="Your Password" name="password1" value="" required>

        <input type="password" id="password2"  placeholder="Sure Password" name="password2" value="" required>

        <div id="errorMessage"></div>

        <button  type="button" onclick="checkPassword()">&nbsp;&nbsp;</button>

</form>


javascript代码:

<script>

function checkPassword(){

var email = document.getElementById("email").value;

var password1 = document.getElementById("password1").value;

var password2 = document.getElementById("password2").value;

var errorMessage;

if(email==""){

errorMessage = document.getElementById("errorMessage");

errorMessage.innerHTML="请输入邮箱!";

}else if(password1 == ""|| password2 == ""){

errorMessage = document.getElementById("errorMessage");

errorMessage.innerHTML="请输入密码!";

}else if(password1 != password2){

errorMessage = document.getElementById("errorMessage");

errorMessage.innerHTML="密码不一致!";

}else{

document.getElementById("signForm").submit();

}

}

</script>


java后台

说明:java程序可以用HttpServletRequest request获得数据,Servlet或者框架都看你自己的项目,return 也看你自己的情况修改

public String doSignIn(HttpServletRequest request){

String username = request.getParameter("email");

String password = request.getParameter("password1");

System.out.println(username+"\n"+password);//替换SQL操作

return "success";

}