JSP 登录与注册的小案例之二(无验证码,前端拦截空参)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP 登录与注册的小案例之二(无验证码,前端拦截空参)相关的知识,希望对你有一定的参考价值。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 代码链接: https://pan.baidu.com/s/1qYB7duO 密码: qfiw --> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.lf.bookstore_test.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <!-- c3p0-config.xml文件配置 --> <c3p0-config> <named-config name="bookstore_c3p0"> <!-- 基本配置 --> <property name="user">LF</property> <property name="password">LF</property> <property name="jdbcUrl">jdbc:oracle:thin:@192.168.10.105:1521:orcl</property> <property name="driverClass">oracle.jdbc.driver.OracleDriver</property> <!-- 配置初始值 --> <property name="initialPoolSize">16</property> <property name="maxPoolSize">25</property> <property name="minPoolSize">10</property> </named-config> </c3p0-config>
package com.lf.bookstore_test.pojo; public class User { private String name;//用户名 private String password;//密码 private String e_mail;//邮箱 //无参构造方法 public User() { } //有参构造方法 public User(String name,String password,String e_mail) { this.name = name; this.password = password; this.e_mail = e_mail; } // set和get方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getE_mail() { return e_mail; } public void setE_mail(String e_mail) { this.e_mail = e_mail; } @Override public String toString() { return "User [name=" + name + ", password=" + password + ", e_mail=" + e_mail + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((e_mail == null) ? 0 : e_mail.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (e_mail == null) { if (other.e_mail != null) return false; } else if (!e_mail.equals(other.e_mail)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; return true; } }
package com.lf.bookstore_test.dao; import com.lf.bookstore_test.pojo.User; public interface UserDao { // 注册 public boolean addUser(User user); //登录 public User queryUser(User user); // 验证用户是否已存在 public boolean queryUserByName(String name); }
package com.lf.bookstore_test.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.lf.bookstore_test.dao.UserDao; import com.lf.bookstore_test.pojo.User; import com.lf.bookstore_test.utils.JdbcUtils; public class UserDaoImpl implements UserDao{ /** * 添加用户 */ @Override public boolean addUser(User user) { //若为空直接返回false if (user==null) return false; //获取连接 Connection connection = JdbcUtils.getConnection(); //创建预编译命令 PreparedStatement pStatement=null; // SQL 语句 String sql = "INSERT INTO BS_USERINFO VALUES(?,?,?)"; int seccessCount=-1; try { pStatement = connection.prepareStatement(sql); // 设置相应的参数 pStatement.setString(1, user.getName()); pStatement.setString(2, user.getPassword()); pStatement.setString(3, user.getE_mail()); //执行SQL语句,返回成功操作的行数 seccessCount = pStatement.executeUpdate(); //大于零,则数据库操作成功 if (seccessCount>0) { return true; } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭相应对象 close(null,pStatement, connection); } return false; } @Override public User queryUser(User user) { //如果name为空直接返回null if (user == null) return null; //创建User User resultUser = null; //获取连接 Connection connection = JdbcUtils.getConnection(); //SQL语句 String sql = "select username,password,email from bs_userinfo where username = ? "; //创建预编译 PreparedStatement pStatement = null; // 创建结果集 ResultSet rSet = null; try { pStatement = connection.prepareStatement(sql); // 设置参数 pStatement.setString(1, user.getName()); // 执行SQL语句 rSet = pStatement.executeQuery(); //遍历 if (rSet.next()) { //创建User resultUser = new User(); //赋值 resultUser.setName(rSet.getString("username")); resultUser.setPassword(rSet.getString("password")); resultUser.setE_mail(rSet.getString("email")); } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭操作 close(rSet,pStatement, connection); } return resultUser; } /** * 根据用户名查询用户是否已存在 * 返回布尔值 */ @Override public boolean queryUserByName(String name) { // name为空时返回false if (name==null) { return false; } //获取连接 Connection connection = JdbcUtils.getConnection(); //SQL语句 String sql = "select username from bs_userinfo where username = ?"; //创建预编译 PreparedStatement pStatement = null; // 创建结果集 ResultSet rSet = null; System.out.println("connection:"+connection); try { pStatement = connection.prepareStatement(sql); // 设置参数 pStatement.setString(1, name); // 执行SQL语句 rSet = pStatement.executeQuery(); //遍历 if (rSet.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭操作 close(rSet,pStatement, connection); } return false; } /** * 实现增删改操作 *//* public boolean userOperation(String sql,Object...ages) { //获取连接 Connection connection = JdbcUtils.getConnection(); //创建预编译命令 PreparedStatement pStatement=null; int seccessCount=-1; try { pStatement = connection.prepareStatement(sql); for (int i = 0; i < ages.length; i++) { // 设置相应的参数 pStatement.setObject(i+1, ages[i]); } //执行SQL语句,返回成功操作的行数 seccessCount = pStatement.executeUpdate(); //大于零,则数据库操作成功 if (seccessCount>0) { return true; } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭相应对象 close(null,pStatement, connection); } return false; } //模糊查询 public List<User> requeryByName(String name) { // name为空时,查询全部数据 name= name==null?"":name; //创建List List<User> list = new ArrayList<User>(); //获取连接 Connection connection = JdbcUtils.getConnection(); //SQL语句 String sql = "select username,password,email from bs_userinfo where username like ?"; //创建预编译 PreparedStatement pStatement = null; // 创建结果集 ResultSet rSet = null; try { pStatement = connection.prepareStatement(sql); // 设置参数 pStatement.setString(1, "%"+name+"%"); // 执行SQL语句 rSet = pStatement.executeQuery(); //遍历 while (rSet.next()) { //创建User类 User user = new User(); //赋值 user.setName(rSet.getString("username")); user.setPassword(rSet.getString("password")); user.setE_mail(rSet.getString("email")); //存入List list.add(user); } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭操作 close(rSet,pStatement, connection); } return list; } */ // 关闭操作 private void close(ResultSet rSet,PreparedStatement pStatement,Connection connection){ //进行相应的关闭(先开后关,后开先关) if (rSet!=null) { try { rSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pStatement!=null){ try { pStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.lf.bookstore_test.service; import com.lf.bookstore_test.pojo.User; public interface UserService { /** * 注册服务 * @param user * @return */ public boolean addUserService(User user); /** * 登录服务 * @param user * @return */ public User QueryUserService(User user); /** * 验证用户是否已存在 * @param name 用户名 * @return */ public boolean queryUserServiceByName(String name); }
package com.lf.bookstore_test.service.impl; import com.lf.bookstore_test.dao.impl.UserDaoImpl; import com.lf.bookstore_test.pojo.User; import com.lf.bookstore_test.service.UserService; /** * * @author lf * */ public class UserServiceImpl implements UserService{ /** * 实现注册服务功能 */ @Override public boolean addUserService(User user) { UserDaoImpl uImpl = new UserDaoImpl(); return uImpl.addUser(user); } /** * 实现查询该用户是否存在功能 */ @Override public User QueryUserService(User user) { UserDaoImpl uImpl = new UserDaoImpl(); User resultUser = uImpl.queryUser(user); return resultUser; } /** * 查询用户是否已被注册 */ @Override public boolean queryUserServiceByName(String name) { UserDaoImpl uImpl = new UserDaoImpl(); return uImpl.queryUserByName(name); } }
package com.lf.bookstore_test.servlet; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lf.bookstore_test.pojo.User; import com.lf.bookstore_test.service.UserService; import com.lf.bookstore_test.service.impl.UserServiceImpl; /** * * @author lf * */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet...doGet..."); /*//获取路径 String servletName = req.getServletPath(); //根据路径截取方法名 String methodName = servletName.substring(1, servletName.length()-3); System.out.println("servletName:"+servletName+",methodName:"+methodName);*/ doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //通过映射的方式调用login或register方法 System.out.println("...doPost..."); //获取路径 String servletName = req.getServletPath(); //根据路径截取方法名 String methodName = servletName.substring(1, servletName.length()-3); System.out.println("servletName:"+servletName+",methodName:"+methodName); Method method = null; try { method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, req,resp); } catch (Exception e) { e.printStackTrace(); } } /** * 登录处理方法 */ private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("登录处理..."); // 获取表单的参数值 String userName = req.getParameter("userName"); String passWord = req.getParameter("passWord"); System.out.println("userName:"+userName+",passWord:"+passWord); // 创建用户 User user = new User(userName, passWord, null); System.err.println("loginUser:"+user); //根据表单的参数值取查询 UserServiceImpl uService = new UserServiceImpl(); User rUser = uService.QueryUserService(user); System.out.println("返回的结果:"+rUser); // 查询结果不为空,则进入下一页面,否则回到原来的页面 if (rUser!=null) { // 保存username req.getSession().setAttribute("user", rUser.getName()); resp.sendRedirect(req.getContextPath()+"/index.jsp");; }else { //提示错误信息 req.setAttribute("tip", "用户名和密码不匹配"); req.getRequestDispatcher("/login.jsp").forward(req, resp); } } /** * 注册处理 */ private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("注册处理..."); //获取表单的值 String userName = req.getParameter("userName"); String passWord = req.getParameter("passWord"); String email = req.getParameter("email"); User user = new User(userName, passWord, email); System.out.println(user); //添加用户,成功进入下一页面,否则回到原来页面 UserServiceImpl uImpl = new UserServiceImpl(); boolean isSuccess = uImpl.addUserService(user); if (isSuccess) { // 存储用户名 req.setAttribute("user", user.getName()); req.getRequestDispatcher("/register_success.jsp").forward(req, resp); }else { req.getRequestDispatcher("/register.jsp").forward(req, resp); } } /** * 检查用户名是否存在 */ private void nameCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ //设置编码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); // System.out.println("检查用户名是否存在"); // 获取表单中的参数值 String userName = req.getParameter("userName"); System.out.println("_____userName:"+userName); //根据表单在的值去查询数据库 UserServiceImpl uImpl = new UserServiceImpl(); boolean isExisted = uImpl.queryUserServiceByName(userName); // System.out.println("isExisted:"+isExisted); // 根据查询结果返回相应的提示 if (isExisted) { resp.getWriter().print("该用户已被注册"); } } }
package com.lf.bookstore_test.utils; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JdbcUtils { /** * 获取数据库连接 * @return */ public static Connection getConnection() { DataSource ds = new ComboPooledDataSource("bookstore_c3p0"); Connection connection = null; try { connection = ds.getConnection(); return connection; } catch (SQLException e) { e.printStackTrace(); } return null; } }
<%@page import="com.lf.bookstore_test.pojo.User"%> <%@page import="com.lf.bookstore_test.service.impl.UserServiceImpl"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link type="text/css" rel="stylesheet" href="css/style.css" /> <script > /* 文档加载完成后再执行方法 */ window.onload=function(){ /* alert(0); */ }; function userNameCheck(){ /* 判断用户名是否已输入 */ var userName = document.getElementsByName("userName")[0]; /* 获取标签 */ var tipNode = document.getElementById("msg"); if(userName.value==""){ /* 提示用户名不能为空 */ tipNode.innerHTML="用户名不能为空哦!"; }else{ tipNode.innerHTML=""; } } function pwdCheck(){ /* 判断密码是否已输入 */ var passWord = document.getElementsByName("passWord")[0]; /* 获取标签 */ var tipNode = document.getElementById("pwdMsg"); if(passWord.value==""){ /* 提示密码不能为空 */ tipNode.innerHTML="亲,密码不能为空哦!"; }else{ tipNode.innerHTML=""; } } function logincheck(){ /* 判断用户名是否已输入 */ var userName = document.getElementsByName("userName")[0]; /* 获取标签 */ var passWord = document.getElementsByName("passWord")[0]; if(userName.value==""){ /* 获取标签 */ var tipNode = document.getElementById("msg"); /* 提示用户名不能为空 */ tipNode.innerHTML="用户名不能为空哦!"; } else{ /* 提示密码不能为空 */ if(passWord.value==""){ /* 获取标签 */ var tipNode = document.getElementById("pwdMsg"); /* 判断密码是否已输入 */ tipNode.innerHTML="亲,密码不能为空哦!"; }else{ return true; } } return false; } </script> </head> <body> <div id="header" class="wrap"> <div id="logo">众软在线图书</div> <div id="navbar"> <form method="get" name="search" action=""> 搜索:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" /> </form> </div> </div> <div id="login"> <h2>用户登陆</h2> <form method="post" action="login.do"> <dl> <dt>用户名:</dt> <dd><input class="input-text" type="text" name="userName" value="${param.userName }" onblur="userNameCheck()"/><span id="msg">${requestScope.tip }</span></dd> <dt>密 码:</dt> <dd><input class="input-text" type="password" name="passWord" value="${param.passWord }" onblur="pwdCheck()"/><span id="pwdMsg"></span></dd> <dt></dt> <dd class="button"><input class="input-btn" type="submit" name="submit" value="" onclick="return logincheck()"/><input class="input-reg" type="button" name="register" value="" onclick="window.location=‘register.jsp‘;" /></dd> </dl> </form> </div> <div id="footer" class="wrap"> 众软在线图书 © 版权所有 </div> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link type="text/css" rel="stylesheet" href="css/style.css" /> <script> /* 下面方法的代码应该重构 */ // 判断用户名是否为空 function userNameCheck(){ /* 判断用户名是否已输入 */ var userName = document.getElementsByName("userName")[0]; /* 获取标签 */ var tipNode = document.getElementById("msg"); if(userName.value==""){ /* 提示用户名不能为空 */ tipNode.innerHTML="用户名不能为空哦!"; }else{ tipNode.innerHTML=""; // 判断用户名是否存在(Ajax局部刷新) //获取对象XMLHttpRequest var request = new XMLHttpRequest(); //打开与服务器的连接 var method = "Get"; var url = "nameCheck.do?userName="+userName.value; request.open(method,url); // 发送请求 request.send(null); //为XMLHttpRequest对象添加onreadystatechange事件 //onreadystatechange事件是服务器状态改变触发的事件 //如果响应,则输出提示 request.onreadystatechange=function(){ //request.readyState==4请求完成 if(request.readyState==4){ //200或者304 代表响应正常 if(request.status==200 || request.status==304){ tipNode.innerHTML=request.responseText; } } }; } } //密码不能为空判断 function pwdCheck(){ /* 判断密码是否已输入 */ var pwd = document.getElementsByName("passWord")[0]; /* 获取标签 */ var tipNode = document.getElementById("pwdMsg"); if(pwd.value==""){ /* 提示密码不能为空 */ tipNode.innerHTML="密码不能为空哦!"; }else{ tipNode.innerHTML=""; } } //确认密码不能为空判断 function rePwdCheck(){ /* 判断确认密码是否已输入 */ var rePwd = document.getElementsByName("rePassWord")[0]; /* 获取标签 */ var tipNode = document.getElementById("rePwdMsg"); if(rePwd.value==""){ /* 提示确认密码不能为空 */ tipNode.innerHTML="确认密码不能为空哦!"; }else{ tipNode.innerHTML=""; } } //email地址不能为空判断 function emailCheck(){ /* 判断email是否已输入 */ var email = document.getElementsByName("email")[0]; /* 获取标签 */ var tipNode = document.getElementById("emailMsg"); if(email.value==""){ /* 提示email不能为空 */ tipNode.innerHTML="email不能为空哦!"; }else{ tipNode.innerHTML=""; //正则表达式判断邮箱 } } function registerCheck(){ /* 判断用户名是否已输入 */ var userName = document.getElementsByName("userName")[0]; /* 判断密码是否已输入 */ var pwd = document.getElementsByName("passWord")[0]; /* 判断确认密码是否已输入 */ var rePwd = document.getElementsByName("rePassWord")[0]; /* 判断email是否已输入 */ var email = document.getElementsByName("email")[0]; // 判断密码与确认密码是否匹配 var isMatched = false; // 判断邮箱是否正确 var isRight = false; if(userName.value==""){ /* 获取标签 */ var tipNode = document.getElementById("msg"); /* 提示用户名不能为空 */ tipNode.innerHTML="用户名不能为空哦!"; } if(pwd.value==""){ /* 获取标签 */ var tipNode = document.getElementById("pwdMsg"); /* 提示密码不能为空 */ tipNode.innerHTML="密码不能为空哦!"; } if(rePwd.value==""){ /* 获取标签 */ var tipNode = document.getElementById("rePwdMsg"); /* 提示确认密码不能为空 */ tipNode.innerHTML="确认密码不能为空哦!"; }else{ //判断密码与确认密码是否匹配 if(pwd.value==rePwd.value){ isMatched = true; }else{ /* 获取标签 */ var tipNode = document.getElementById("pwdMsg"); /* 提示密码不能为空 */ tipNode.innerHTML="密码不匹配哦!"; } } if(email.value==""){ /* 获取标签 */ var tipNode = document.getElementById("emailMsg"); /* 提示email不能为空 */ tipNode.innerHTML="email不能为空哦!"; }else{ /* 判断邮箱是否匹配 */ // 使用正则表达式判断邮箱 var regex = /^([a-zA-Z0-9_-])[email protected]([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/; isRight = regex.test(email.value); if(isRight==false){ /* 获取标签 */ var tipNode = document.getElementById("emailMsg"); /* 提示email不能为空 */ tipNode.innerHTML="email不正确哦!"; } } // if(userName.value!="" && isMatched && isRight){ return true; } return false; } </script> </head> <body> <div id="header" class="wrap"> <div id="logo">众软在线图书</div> <div id="navbar"> <form method="get" name="search" action=""> 搜索:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" /> </form> </div> </div> <div id="register"> <div class="title"> <h2>欢迎注册众软在线图书</h2> </div> <div class="steps"> <ul class="clearfix"> <li class="current">1.填写注册信息</li> <li class="unpass">2.注册成功</li> </ul> </div> <form method="post" action="register.do"> <dl> <dt>用 户 名:</dt> <dd><input class="input-text" type="text" name="userName" value="${param.userName }" onblur="userNameCheck()"/><span id="msg">${requestScope.userMsg }</span></dd> <dt>密 码:</dt> <dd><input class="input-text" type="password" name="passWord" value="${param.passWord }" onblur="pwdCheck()"/><span id="pwdMsg">${requestScope.pwdMsg }</span></dd> <dt>确认密码:</dt> <dd><input class="input-text" type="password" name="rePassWord" value="${param.rePassWord }" onblur="rePwdCheck()"/><span id="rePwdMsg">${requestScope.rePwdMsg }</span></dd> <dt>Email地址:</dt> <dd><input class="input-text" type="text" name="email" value="${param.email }" onblur="emailCheck()"/><span id="emailMsg">${requestScope.emailMsg }</span></dd> <dt></dt> <dd class="button"><input class="input-reg" type="submit" name="register" value="" onclick="return registerCheck()"/></dd> </dl> </form> </div> <div id="footer" class="wrap"> 众软在线图书 © 版权所有 </div> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> Welcome to my webSite <br> </body> </html>
以上是关于JSP 登录与注册的小案例之二(无验证码,前端拦截空参)的主要内容,如果未能解决你的问题,请参考以下文章