注册用户
1.前端页面
<!DOCTYPE html> <html> <head> <title>注册页面</title> <script src="js/jquery-3.6.0.min.js"></script> <meta charset="UTF-8"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <style type="text/css"> body{ background-image: url(/images/img_1.png); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-color: #CCCCCC; } #user_reg{ font-family: 微软雅黑; font-size: 40px; text-align: center; margin-left: -150px; margin-top: 200px; } form{ width: 500px; margin: 40px auto auto auto; font-size: 25px; } input{ height: 30px; width: 12em; margin-top: 5px; margin-bottom: 5px; } input[type="submit"],input[type="reset"]{ height: 25px; width: 5em; margin-top: 5px; margin-left: 6px; } </style><script type="text/javascript"> function validate_email(email){ var emailReg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; if(email !="" && email.search(emailReg) != -1) { document.getElementById("test_email").innerHTML = "<font color='green' size='3px'>√邮箱格式正确</font>"; }else{ document.getElementById("test_email").innerHTML = "<font color='red' size='3px'>邮箱格式错误</font>"; } } function validate_username(username){ var usernameReg=/^\w{8,20}$/; if(username !="" && username.search(usernameReg) != -1) { document.getElementById("test_user").innerHTML = "<font color='green' size='3px'>√用户名格式正确</font>"; }else{ document.getElementById("test_user").innerHTML = "<font color='red' size='3px'>用户名格式错误</font>"; } } function validate_password(password){ var passwordReg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/; if(password != "" && password.search(passwordReg) != -1) { document.getElementById("test_pw").innerHTML = "<font color='green' size='3px'>√密码格式正确</font>"; }else{ document.getElementById("test_pw").innerHTML = "<font color='red' size='3px'>密码格式错误</font>"; alert("密码有8-20位,由数字和字母组成!"); } } function validate_password2(password2){ var password = document.getElementById("password").value; //测试:console.log(password); //测试:console.log(password2); if (password == ""){ document.getElementById("is_test_pw").innerHTML = "<font color='red' size='3px'>密码不为空</font>"; }else if(password==password2){ document.getElementById("is_test_pw").innerHTML = "<font color='green' size='3px'>√两次输入的密码相同</font>"; }else{ document.getElementById("is_test_pw").innerHTML = "<font color='red' size='3px'>两次输入的密码不相同</font>"; console.log("密码有8-20位,由数字和字母组成!"); } } function validate_form() { var email = document.getElementById("email").value; var username = document.getElementById("username").value; var password = document.getElementById("password").value; var password2 = document.getElementById("password2").value; var usernameReg = /^\w{8,20}$/; var emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; var passwordReg =/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/; if (email != "" && emailReg.test(email)) { if (username != "" && usernameReg.test(username)) { if (password != "" && passwordReg.test(password)) { if (password2 == password) { alert("信息填写正确,可以正常提交!"); console.log("信息填写正确,可以正常提交!"); return true; } else { alert("密码不一致,提交失败,请重新填写!"); console.log("密码不一致,提交失败,请重新填写!"); return false; } } else { alert("密码格式错误,提交失败,请重新填写!"); console.log("密码格式错误,提交失败,请重新填写!"); return false; } } else { alert("注册的账号不符合要求,提交失败,请重新填写!"); console.log("注册的账号不符合要求,提交失败,请重新填写!"); return false; } } } $(function (){ $("#registerForm").submit(function (){ if (checkUsername()&& checkPassword()&&checkEmail()){ $.post("registUserServlet",$(this).serialize(),function (data) { //处理服务器响应数据 data {flag:true,errorMsg:"注册失败"} if (data["flag"]){ //注册成功,跳转成功页面 window.location.herf="register_ok.html"; }else { //注册失败,给errorMsg添加提示信息、 $("#errorMsg").html(data["errorMsg"]) } }); } //跳转页面 return false; }); //当一个组件失去焦点时,调用对应的校验方法 $("#username").blur(checkUsername()); $("#password").blur(checkPassword()); $("#email").blur(checkEmail()); }) </script> </head> <body> <div id="user_reg">宿舍小超市用户注册:</div> <form id="registerForm" action="register_ok.html" > <input type="hidden" name="action" value="register"> <table> <tr> <td>请输入用户名</td> <td><input type="text" id="username" name="username" placeholder="只能用邮箱注册" onblur="validate_username(this.value)"/></td> <td id="test_user"></td> </tr> <tr> <td>请输入邮箱</td> <td><input type="text" id="email" name="email" placeholder="只能用邮箱注册" onblur="validate_email(this.value)"/></td> <td id="test_email"></td> </tr> <tr> <td>请输入密码:</td> <td><input type="password" id="password" name="password" placeholder="8位密码由数字和字母组成" onblur="validate_password(this.value)"/></td> <td id="test_pw"></td> </tr> <tr> <td>请确认密码:</td> <td><input type="password" id="password2" name="password2" onblur="validate_password2(this.value)" /></td> <td id="is_test_pw"></td> </tr> <tr> <td ><input type="submit" id="submit_form" value="注册" onclick="return validate_form()"/> <input type="reset" value="重置"/> </td> </tr> </table> </form> </body> </html>
2.后端代码
package web.servelet; public class User { private String username; private String password; private String uid; private String email; public User(String username,String password) { this.username = username; this.password = password; } public User(){ } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", uid='" + uid + '\'' + ", email='" + email + '\'' + '}'; } }
package Dao.impl; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import Dao.UserDao; import utils.JDBCUtils; import web.servelet.User; public class UserDaoImpl implements UserDao { private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource()); @Override public User findByUsername(String username) { User user=null; //定义sql try { String sql="select * from user where username=?"; //执行sql user=template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),username); } catch (Exception e) { e.printStackTrace(); } return user; } @Override public void save(User user) { //定义sql String sql = "insert into user(username,password,email) values (?,?,?)"; //执行sql template.update(sql, user.getUsername(), user.getPassword(), user.getEmail() ); } @Override public User findByUsernameAndPassword(String username, String password) { User user = null; try { String sql = "SELECT * FROM user WHERE username = ? AND password = ?"; user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username, password); } catch (DataAccessException e) { e.printStackTrace(); } return user; } }
用户登录
1.前端页面
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>用户登录</title> <link rel="stylesheet" type="text/css" href="css/common.css"> <link rel="stylesheet" type="text/css" href="css/login.css"> <link rel="stylesheet" type="text/css" href="css/header.css"> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <script src="js/angular.min.js"></script> <script src="js/jquery-3.3.1.js"></script> <script> $(function () { // 1.给登录按钮绑定事件 $("#btn_sub").click(function () { // 2.发送ajax请求,提交表单数据 $.post("loginServlet", $("#loginForm").serialize(), function (resultInfo) { // resultInfo: {flag:true/false, errorMsg, "..."} // 3.处理响应结果 if (resultInfo["flag"]) { // 登陆成功 window.location.href = "index.html"; } else { // 登陆失败.. $("#errorMsg").html(resultInfo["errorMsg"]); } }); }); }); </script> </head> <body> <!--引入头部--> <div id="header"></div> <!-- 头部 end --> <section id="login_wrap"> <div class="fullscreen-bg" style="background: url(images/img_1.png);height: 800px;"> </div> <div class="login-box"> <div class="title"> <span>欢迎登录宿舍小超市</span> </div> <div class="login_inner"> <!--登录错误提示消息--> <div id="errorMsg" class="alert alert-danger" ></div> <form id="loginForm" action="" method="post" accept-charset="utf-8"> <input type="hidden" name="action" value="login"/> <label> <input name="username" type="text" placeholder="请输入账号" autocomplete="off"> </label> <label> <input name="password" type="text" placeholder="请输入密码" autocomplete="off"> </label> <div class="submit_btn"> <button type="button" id="btn_sub">登录</button> <div class="auto_login"> <label> <input type="checkbox" name="auto_login" class="checkbox"> </label> <span>自动登录</span> </div> </div> </form> <div class="reg">没有账户?<a href="register.html">立即注册</a></div> </div> </div> </section> <div id="footer"></div> <script src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="js/include.js"></script> </body> </html>
2.后端代码
package demo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import service.UserService; import service.impl.UserServiceImpl; import web.servelet.ResultInfo; import web.servelet.User; 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 javax.servlet.http.HttpSession; import java.lang.reflect.InvocationTargetException; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; @WebServlet("/loginServlet/*") public class loginServlet extends HttpServlet { ObjectMapper mapper = new ObjectMapper(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户名和密码数据 Map<String,String[]> map=request.getParameterMap(); HttpSession session = request.getSession(); //封装User对象 User user=new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //调用service查询 // 3.调用service查询user UserService service=new UserServiceImpl(); User loginUser = service.login(user); ResultInfo resultInfo=new ResultInfo(); // 4.判断用户是否存在 if (loginUser == null) { // 用户不存在 resultInfo.setFlag(false); resultInfo.setErrorMsg("用户名或密码错误!"); } // else 用户存在 if (loginUser != null ) { resultInfo.setFlag(true); session.setAttribute("user", loginUser); } String json = mapper.writeValueAsString(resultInfo); System.out.println(json); response.setContentType("application/json:charset:utf-8"); mapper.writeValue(response.getOutputStream(), resultInfo); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }