javaweb实现注册页面(数据库连接以及ajax验证)
先放效果图 ? ? ? ?可实现js实时验证 ? ? ? ? ? ? ? 可实现ajax实时验证注册信息是否存在 ? ? ?页面实现要求 1登录账号:要求由6到12位字母、数字、下划线组成,只有字母可以开头;(1分) 2登录密码:要求显示“? ”或“*”表示输入位数,密码要求八位以上字母、数字组成。(1分) 3性别:要求用单选框或下拉框实现,选项只有“男”或“女”;(1分) 4学号:要求八位数字组成,前四位为“2018”开头,输入自己学号;(1分) 5姓名:输入自己的姓名; 5电子邮箱:要求判断正确格式[email?protected];(1分) 6点击“添加”按钮,将学生个人信息存储到数据库中。(3分) 7可以演示连接上数据库。(2分) 实现思路 ? ?实现的思路非常简单,前端做好表单及js验证,后端接收表单填写数据并插入数据库 ?难点:ajax实时验证primary key对应列内容在数据库中是否已经存在,若存在,则提示错误信息 ? ? 下面贴上代码: 首先是前端页面代码: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <title>添加信息</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script> <script src="./js/jquery.min.js"></script> <style> body{ background-image:url(./library/3d效果/QQ图片20191015211520.jpg); } .container{ margin-top:100px; border-radius:10px; padding-top:50px; padding-bottom:50px; align:center; background-color:white; opacity:0.8; width:500px; } form{ margin-top:20px; } .form-group{ align:center; width:350px; margin:auto; position:relative; } h2{ border-bottom:5px solid red; padding-bottom:10px; text-align:center; width:100%; } .label{ float:left; width:80px; margin-top:7px; margin-right:5px; text-align:left; } .form-control{ width:200px; margin-top:7px; } .sex{ border:0px solid #000; width:200px; margin-top:7px; } .sign{ width:160px; margin-top:10px; } .tip{ position:relative; width:100%; height:auto; padding:5px; } .tip .tipicon{ float:left; background-image:url(img/warn.png); background-repeat:no-repeat; background-position:center; background-size:cover; width:20px; height:20px; } .tipmessage{ color:red; font-size:15px; } .tip{ display:none; } .righttip{ display:none; position:absolute; right:8px; top:8px; width:25px; height:25px; background-image:url(img/zhengque.png); background-repeat:no-repeat; background-position:center; background-size:cover; } </style> <script type="text/javascript"> function isMobileNumber(phone) { var flag = false; var message = ""; var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+d{8})$/; if (myreg.test(phone)){ flag = true; } return flag; } function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"); var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配 var context = ""; if (r != null) context = r[2]; reg = null; r = null; return context == null || context == "" || context == "undefined" ? "" : context; } function isEmail(email){ //对电子邮件的验证 var myreg = /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9][email?protected]([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$/; if(!myreg.test(email)){ return false; } else return true; } function isPwd(password) { var myreg=/[0-9a-zA-Z]+/; if(!myreg.test(password)) return false; else return true; } function isId(id) { if((id[0]=="2")&&(id[1]=="0")&&(id[2]=="1")&&(id[3]=="8")) return true; else return false; } function inputusername() { var username=$("#usr").val(); var tip1=$("#tip1"); var tip_1=$("#tip_1"); if(!((username[0]>=‘a‘&&username[0]<=‘z‘)||(username[0]>=‘A‘&&username[0]<=‘Z‘))) { $("#usr").next().css("display","none"); tip1.css("display","block"); tip_1.html("用户名必须以英文字母开头!"); } else if(username.length<6||username.length>12){ $("#usr").next().css("display","block"); tip_1.html("用户名必须为6-12位字符!"); } else { tip1.css("display","none"); $.post( "UserServlet",{username:username},function(data){ if(data=="yes"){ tip1.css("display","none"); $("#usr").next().css("display","block"); } else{ $("#usr").next().css("display","none"); tip1.css("display","block"); tip_1.html("用户名已被注册!"); } },"text" ); } } function inputId() { var id=$("#id").val(); var tip4=$("#tip4"); var tip_4=$("#tip_4"); if(!isId(id)) { $("#id").next().css("display","none"); tip4.css("display","block"); tip_4.html("学号必须以2018开头!"); } else if(id.length!=8){ $("#id").next().css("display","block"); tip_4.html("请输入8位学号!"); } else { tip4.css("display","none"); $.post( "IdServlet",{id:id},function(data){ if(data=="yes"){ tip4.css("display","none"); $("#id").next().css("display","block"); } else{ $("#id").next().css("display","none"); tip4.css("display","block"); tip_4.html("该学号已存在!"); } },"text" ); } } function inputpassword() { var password=$("#pwd").val(); var tip2=$("#tip2"); var tip_2=$("#tip_2"); if(password.length<8) { $("#pwd").next().css("display","none"); tip2.css("display","block"); tip_2.html("请输入8位以上密码!"); } else if(!isPwd(password)){ $("#pwd").next().css("display","block"); tip_2.html("密码仅由英文或数字组成!"); } else{ tip2.css("display","none"); $("#pwd").next().css("display","block"); } } function inputmobile() { var mobile=$("#mobile").val(); var tip4=$("#tip4"); var tip_4=$("#tip_4"); if(mobile.length!=11) { $("#mobile").next().css("display","block"); tip_4.html("请输入11位手机号!"); } else if(isMobileNumber(mobile)==false){ $("#mobile").next().css("display","block"); tip_4.html("手机号格式不正确!"); } else { tip4.css("display","none"); $.post( "MobileServlet",{mobile:mobile},"none"); $("#mobile").next().css("display","block"); tip_4.html("手机号已被注册!"); } },"text" ); } } function inputemail() { var email=$("#email").val(); var tip5=$("#tip5"); var tip_5=$("#tip_5"); if(!isEmail(email)) { $("#email").next().css("display","none"); tip5.css("display","block"); tip_5.html("邮箱格式不正确!"); } else { tip5.css("display","none"); $.post( "EmailServlet",{email:email},function(data){ if(data=="yes"){ tip5.css("display","none"); $("#email").next().css("display","block"); } else{ $("#email").next().css("display","none"); tip5.css("display","block"); tip_5.html("邮箱已被注册!"); } },"text" ); } } function isEmpty() { if($("#usr").val()==""||$("#pwd").val()==""||$("#name").val()==""||$(‘input[name="sex"]:checked‘).val()==""||$("#sel1").val()==""|| $("#agency").val()==""||$("#major").val()==""||$("#classnum").val()==""||$("#birthplace").val()=="" ||$("#email").val()==""||$("#id").val()==""||$("#text").val()=="") { alert("请将信息填写完整!"); return false; } return true; } function getResult() { if(GetQueryString("result")=="true") alert("添加成功!"); else if(GetQueryString("result")=="false") alert("添加失败!"); } var inputs=document.getElementsByTagName("input"); for(var i=0;i<inputs.length;i++) { inputs[i].onkeyup=function(event){ if(event.keyCode=13){ var next=this.nextElementSibling.nextElementSibling; next.focus(); } } } </script> </head> <body onload="getResult()"> <div class="container"> <h2>用户注册</h2> <form action="Signin_do" method="post"> <div class="form-group"> <label for="usr" class="label">账号:</label> <input type="text" class="form-control" id="usr" name="username" oninput="inputusername()" placeholder="请输入用户名"> <div class="righttip"></div> <div class="tip" id="tip1"> <div class="tipicon"></div> <div id="tip_1" class="tipmessage"></div> </div> </div> <div class="form-group"> <label for="pwd" class="label">密码:</label> <input type="password" class="form-control" id="pwd" name="password" placeholder="请输入密码" oninput="inputpassword()"> <div class="righttip"></div> <div class="tip" id="tip2"> <div class="tipicon"></div> <div id="tip_2" class="tipmessage"></div> </div> </div> <div class="form-group"> <label class="label" for="sex">性别:</label> <div class="sex form-control" id="sex"> <label class="radio-inline"><input type="radio" name="sex" value="男">男</label> <label class="radio-inline"><input type="radio" name="sex" value="女">女</label> </div> </div> <div class="form-group"> <label for="name" class="label">姓名:</label> <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"> </div> <div class="form-group"> <label for="name" class="label">学号:</label> <input type="text" class="form-control" id="id" name="id" placeholder="请输入学号" oninput="inputId()"> <div class="righttip"></div> <div class="tip" id="tip4"> <div class="tipicon"></div> <div id="tip_4" class="tipmessage"></div> </div> </div> <div class="form-group"> <label for="email" class="label">电子邮件:</label> <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱" oninput="inputemail()"> <div class="righttip"></div> <div class="tip" id="tip5"> <div class="tipicon"></div> <div id="tip_5" class="tipmessage"></div> </div> </div> <div class="form-group"> <label for="email" class="label">所在学院:</label> <input type="text" class="form-control" id="agency" name="agency" placeholder="请输入学院" oninput="inputemail()"> </div> <div class="form-group"> <label for="email" class="label">所在系:</label> <input type="text" class="form-control" id="major" name="major" placeholder="请输入系" oninput="inputemail()"> </div> <div class="form-group"> <label for="email" class="label">所在班级:</label> <input type="text" class="form-control" id="classnum" name="classnum" placeholder="请输入班级" oninput="inputemail()"> </div> <div class="form-group"> <label for="sel1" class="label">入学年份(届):</label> <select class="form-control" id="sel1" name="year"> <option value="1998">1998</option> <option value="1999">1999</option> <option value="2000">2000</option> <option value="2001">2001</option> </select> 届 </div> <div class="form-group"> <label for="email" class="label">生源地:</label> <input type="text" class="form-control" id="birthplace" name="birthplace" placeholder="请输入生源地" oninput="inputemail()"> <div class="righttip"></div> <div class="tip" id="tip5"> <div class="tipicon"></div> <div id="tip_5" class="tipmessage"></div> </div> </div> <div class="form-group"> <label for="email" class="label">备注:</label> <input type="text" class="form-control" id="text" name="text" oninput="inputemail()"> <div class="righttip"></div> <div class="tip" id="tip5"> <div class="tipicon"></div> <div id="tip_5" class="tipmessage"></div> </div> </div> <input type="submit" class="sign btn btn-primary btn-lg" value="添加" onclick="return isEmpty()"> </form> </div> </body> </html> 然后是处理表单提交的servlet(Signin_do)代码: package com.manage.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.DBUtil.java.DBUtil; import com.information.javabean.People; /** * Servlet implementation class Signin_do */ @WebServlet("/Signin_do") public class Signin_do extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); String password=request.getParameter("password"); String sex=request.getParameter("sex"); String name=request.getParameter("name"); String id=request.getParameter("id"); String email=request.getParameter("email"); String agency=request.getParameter("agency"); String major=request.getParameter("major"); String classnum=request.getParameter("classnum"); String year=request.getParameter("year"); String birthplace=request.getParameter("birthplace"); String text=request.getParameter("text"); if(DBUtil.addInformation(username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text)) response.sendRedirect("NewFile.jsp?result=true"); else response.sendRedirect("NewFile.jsp?result=false"); } /** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response) */ protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub doGet(request,response); } } 然后是ajax判断学号是否存在的servlet(IdServlet)代码: package com.manage.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.DBUtil.java.DBUtil; /** * Servlet implementation class IdServlet */ @WebServlet("/IdServlet") public class IdServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,IOException { // TODO Auto-generated method stub String id=request.getParameter("id"); if(DBUtil.getId(id)) response.getWriter().write("no"); else response.getWriter().write("yes"); } /** * @see HttpServlet#doPost(HttpServletRequest request,response); } } ajax接收判断账号是否存在的servlet(UserServlet): package com.manage.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.DBUtil.java.DBUtil; /** * Servlet implementation class UserServlet */ @WebServlet("/UserServlet") public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,IOException { // TODO Auto-generated method stub String username=request.getParameter("username"); System.out.println(username); //DBUtil.getUsername(username); if(DBUtil.getUsername(username)) response.getWriter().write("no"); else response.getWriter().write("yes"); } /** * @see HttpServlet#doPost(HttpServletRequest request,response); } } 然后是ajax判断邮箱是否存在的servlet(EmailServlet)代码: ? package com.manage.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.DBUtil.java.DBUtil; /** * Servlet implementation class EmailServlet */ @WebServlet("/EmailServlet") public class EmailServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { // TODO Auto-generated method stub String email=request.getParameter("email"); if(DBUtil.getEmail(email)) response.getWriter().write("no"); else response.getWriter().write("yes"); } /** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response) */ protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub doGet(request,response); } } 数据库操作类DBUtil类代码: package com.DBUtil.java; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.information.javabean.People; import sun.net.www.content.text.plain; public class DBUtil { //数据库URL和账号密码 public static final String connectionURL="jdbc:mysql://localhost:3306/people_information_db?useUnicode=true&characterEncoding=GB18030&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true"; public static final String username="root"; public static final String password="010218"; //数据库连接 public static Connection getConnection() { try { Class.forName("com.mysql.cj.jdbc.Driver"); //Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(connectionURL,username,password); } catch (Exception e) { // TODO: handle exception System.out.println("数据库连接失败"); e.printStackTrace(); } return null; } public static boolean Signin(String username,String password,String name,String sex,String province,String mobile,String email) { Connection con=null; PreparedStatement pstmt=null; try { con=getConnection(); String sql="insert into signin_users (username,province,mobile,email) values (‘"+ username+"‘,‘"+password+"‘,‘"+name+"‘,‘"+sex+"‘,‘"+province+"‘,‘"+mobile+"‘,‘"+email+"‘)"; System.out.println(sql); pstmt=con.prepareStatement(sql); pstmt.executeUpdate(); return true; } catch(SQLException e) { e.printStackTrace(); } return false; } public static boolean getUsername(String username) { Connection connection=null; PreparedStatement preparedStatement=null; ResultSet rSet=null; try { connection=getConnection(); String sql="select * from signin_users where username="+"‘"+username+"‘"; System.out.println(sql); preparedStatement=connection.prepareStatement(sql); rSet=preparedStatement.executeQuery(); if(rSet.next()) return true; else return false; } catch(SQLException e) { e.printStackTrace(); } return false; } public static boolean getMobile(String mobile) { Connection connection=null; PreparedStatement preparedStatement=null; ResultSet rSet=null; try { connection=getConnection(); String sql="select * from signin_users where mobile="+"‘"+mobile+"‘"; System.out.println(sql); preparedStatement=connection.prepareStatement(sql); rSet=preparedStatement.executeQuery(); if(rSet.next()) return true; else return false; } catch(SQLException e) { e.printStackTrace(); } return false; } public static boolean getEmail(String email) { Connection connection=null; PreparedStatement preparedStatement=null; ResultSet rSet=null; try { connection=getConnection(); String sql="select * from signin_users where email="+"‘"+email+"‘"; System.out.println(sql); preparedStatement=connection.prepareStatement(sql); rSet=preparedStatement.executeQuery(); if(rSet.next()) return true; else return false; } catch(SQLException e) { e.printStackTrace(); } return false; } public static boolean getId(String id) { Connection connection=null; PreparedStatement preparedStatement=null; ResultSet rSet=null; try { connection=getConnection(); String sql="select * from signin_users where id="+"‘"+id+"‘"; System.out.println(sql); preparedStatement=connection.prepareStatement(sql); rSet=preparedStatement.executeQuery(); if(rSet.next()) return true; else return false; } catch(SQLException e) { e.printStackTrace(); } return false; } public static boolean addInformation(String username,String id,String email,String agency,String major,String classnum,String year,String birthplace,String text) { Connection con=null; PreparedStatement pstmt=null; try { con=getConnection(); String sql="insert into signin_users (username,text) values (‘"+ username+"‘,‘"+id+"‘,‘"+email+"‘,‘"+agency+"‘,‘"+major+"‘,‘"+classnum+"‘,‘"+year+"‘,‘"+birthplace+"‘,‘"+text+"‘)"; System.out.println(sql); pstmt=con.prepareStatement(sql); pstmt.executeUpdate(); return true; } catch(SQLException e) { e.printStackTrace(); } return false; } public static void main(String[] args) { addInformation("1","1","1"); } } 以上就是注册页面实现需要的所有代码了 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |