JSP 登录与注册的小案例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP 登录与注册的小案例相关的知识,希望对你有一定的参考价值。
源代码连接地址如下:链接:http://pan.baidu.com/s/1nvEuHBj 密码:qsr1
#properties文件 driver=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@192.168.10.105:1521:orcl user=LF password=LF
package com.lf.newhw; 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.newhw; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sound.midi.Patch; public class VerifyCode { //验证码字符的个数 private static int count = 4; //干扰线的条数 private static int lines = 2; /** * 随机产生颜色 * @return 颜色 */ private static Color getRandomColor(){ Random random = new Random(); Color color = new Color(random.nextInt(255)+1, random.nextInt(255)+1, random.nextInt(255)+1); return color; } /** * 获取四个字符的字符串 * @return 字符串 */ public static String getForthWord() { String string = "23456789abcdefghijkmnpqrstuvwxyz"; StringBuilder newStr = new StringBuilder(""); //随机获取count个数字,根据count个随机数产生字符串 Random random = new Random(); for (int i = 0; i < count; i++) { int ranNum=random.nextInt(string.length()); newStr.append(string.charAt(ranNum)); } String str = new String(newStr); return str; } /** * 绘画验证码 * @return BufferedImage */ public static BufferedImage productImage(String verifyCode) { int width = 70; int height = 30; // 得到图片缓存区 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 得到它的绘制环境(这张图片的笔) Graphics2D g2 = (Graphics2D)bi.getGraphics(); // 设置颜色 g2.setColor(Color.WHITE); // 填充整张图片(其实就是设置背景颜色) g2.fillRect(0, 0, width, height); // 设置字体 g2.setFont(new Font("宋体", Font.BOLD, 25)); //设置颜色 g2.setColor(VerifyCode.getRandomColor()); // 向图片写字符串 g2.drawString(verifyCode, 7, 25); //画两条干扰线 Random random = new Random(); for (int i = 0; i < lines; i++) { g2.drawLine(2, random.nextInt(height-10)+10, width-5, random.nextInt(height)); } return bi; } }
package com.lf.newhw.jdbc; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DBUtils { //文documentName private static String defalutName = "dbutils.properties"; //get Connection by default document name public static Connection getConnection() { Connection connection = getConnection(defalutName); return connection; } //get Connection by document name private static Connection getConnection(String fileName) { // io流读取属性文件 InputStream in = DBUtils.class.getClassLoader().getResourceAsStream(fileName); //读取文件里的内容 Properties p = new Properties(); try { p.load(in); } catch (IOException e) { e.printStackTrace(); } //通过键值对获取相应的值 String url = p.getProperty("url"); String user = p.getProperty("user"); String password = p.getProperty("password"); String driver = p.getProperty("driver"); System.out.println(driver); // 通过映射获取相应的类 try { System.out.println(driver); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } Connection connection = null; // 生成Connection try { connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭io流 try { if (in!=null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return connection; } }
package com.lf.newhw.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.lf.newhw.User; public class UserDao { public static User requeryUser (String sql,Object...args) { List<User> list = UserDao.requerUsers(sql, args); User user = null; for (int i = 0; i < list.size(); i++) { user = (User)list.get(0); // System.out.println(user); } return user; } //增删改操作 public static void userOperation(String sql,Object...args) { //获取连接 Connection connection = DBUtils.getConnection(); //创建PreparedStatement对象 PreparedStatement pStatement = null; try { pStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { //数据库的列从1开始 pStatement.setObject(i+1,args[i]); } //执行sql语句 pStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ // 关闭相应对象 try { if (pStatement!=null) pStatement.close(); if (connection!=null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static List<User> requerUsers(String sql,Object...args) { // 创建List List<User> list = new ArrayList<User>(); // String sql = "select * from users"; //获取connection Connection connection = DBUtils.getConnection(); //创建PreparedStatement对象 PreparedStatement pStatement = null; ResultSet rSet = null; try { pStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { try { pStatement.setObject(i+1, args[i]); } catch (SQLException e) { e.printStackTrace(); } } // 结果集 rSet = pStatement.executeQuery(); while (rSet.next()) { //打印 // System.out.println(rSet.getString(1)+" "+rSet.getString(2)+" "+rSet.getString(3)); //把数据转成user类的实例对象 // 创建User对象 User user = new User(rSet.getString(1), rSet.getString(2), rSet.getString(3)); //把user对象存入list list.add(user); } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭相应对象 try { if (pStatement!=null) pStatement.close(); if (connection!=null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } // 查询 public static List<User> requeryUsers() { // 创建List List<User> list = new ArrayList<User>(); String sql = "select * from users"; //获取connection Connection connection = DBUtils.getConnection(); //创建PreparedStatement对象 PreparedStatement pStatement = null; ResultSet rSet = null; try { pStatement = connection.prepareStatement(sql); // 结果集 rSet = pStatement.executeQuery(); while (rSet.next()) { //打印 // System.out.println(rSet.getString(1)+" "+rSet.getString(2)+" "+rSet.getString(3)); //把数据转成user类的实例对象 // 创建User对象 User user = new User(rSet.getString(1), rSet.getString(2), rSet.getString(3)); //把user对象存入list list.add(user); } } catch (SQLException e) { e.printStackTrace(); }finally{ //关闭相应对象 try { if (pStatement!=null) pStatement.close(); if (connection!=null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } }
package com.lf.newhw.servlet; import java.io.IOException; import java.sql.Driver; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lf.newhw.User; import com.lf.newhw.jdbc.UserDao; public class LoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost。。。"); // 获取表单中相应的值 String uerName = req.getParameter("username"); String password = req.getParameter("password"); // String email = req.getParameter("e-mail"); String verifyCode = req.getParameter("verifyCode"); // 将对应的值存起来,便于表单回写 req.getSession().setAttribute("username", uerName); req.getSession().setAttribute("password", password); // req.getSession().setAttribute("e-mail", email); //从数据库里获取数据 String sql="select * from users where username=? and pwd=?"; Object[] objects = {uerName,password}; User user = UserDao.requeryUser(sql, objects); //把用户信息保存起来 req.getSession().setAttribute("user", user); // System.out.println("user:"+user); //获取验证码 String code = (String)req.getSession().getAttribute("verifyCode"); // System.out.println("code:"+code+" verifyCode:"+verifyCode); String msg = null; msg = user==null?"用户名或密码错误":(code.equalsIgnoreCase(verifyCode)?"":"验证码错误"); System.out.println("msg:"+msg); if (msg=="") { // 转发 req.getRequestDispatcher("/index.jsp").forward(req, resp); }else { // 重定向 resp.sendRedirect(req.getContextPath()+"/login.jsp"); //把msg存入session req.getSession().setAttribute("msg", msg); } } }
package com.lf.newhw.servlet; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.net.aso.p; import com.lf.newhw.User; import com.lf.newhw.jdbc.UserDao; public class RegisterServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 进行注册操作 // 获取表单中相应的值 String rName = req.getParameter("rname"); String password = req.getParameter("rpassword"); String pwd = req.getParameter("rpwd"); String email = req.getParameter("remail"); System.out.println(rName+" "+password+" "+pwd+" "+email); // 将对应的值存起来,便于表单回写 req.getSession().setAttribute("rname", rName); req.getSession().setAttribute("rpassword", password); req.getSession().setAttribute("rpwd", pwd); req.getSession().setAttribute("remail", email); //从数据库里获取数据(如果没有相关用户名则可存入数据库) String sql="select * from users where username=?"; Object[] objects = {rName}; User user = UserDao.requeryUser(sql, objects); // String tipMsg = null; System.out.println("rName:"+rName); //如果为空提示 if (rName=="" || password=="" || pwd=="" || email=="") { tipMsg = "选项不能为空"; System.out.println("=============:"); } System.out.println("===tipMsg:"+tipMsg); // 如果不为空字段往下执行 if (tipMsg==null) { System.out.println("+_+user:"+user); tipMsg = user!=null?"该用户已存在":""; System.out.println("----tipMsg:"+tipMsg); // 如果用户名不存在,就判断密码 if (tipMsg=="") { // 判断密码 if (password!=null) { tipMsg= password.equals(pwd)?"":"密码不匹配"; } System.out.println("+_+++tipMsg:"+tipMsg); // 如果密码匹配正确,判断邮箱 if (tipMsg=="") { // 使用正则表达式判断邮箱 String check = "^[a-z\\d]+(\\.[a-z\\d]+)*@([\\da-z](-[\\da-z])?)+(\\.{1,2}[a-z]+)+$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); boolean isMatched = matcher.matches(); tipMsg = isMatched?"":"输入的邮箱有误!"; System.out.println("正则表达式isMatched:"+isMatched+",tipMsg"+tipMsg); } } if (tipMsg=="") { //无误,进行存储 String sqlString = "insert into users values(?,?,?)"; Object[] objects2={rName,password,email}; UserDao.userOperation(sqlString, objects2); tipMsg="已录入"; } } System.out.println("end+tipMsg:"+tipMsg); // 存储提示信息 req.getSession().setAttribute("tipMsg", tipMsg); resp.sendRedirect(req.getContextPath()+"/register.jsp"); } }
package com.lf.newhw.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lf.newhw.jdbc.UserDao; public class UpdateServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("============doPost"); // 获取表单的值 String name = req.getParameter("updatename"); String password = req.getParameter("updatepwd"); String eMail = req.getParameter("updateEmail"); // 获取用户名(初始值) String username = (String)req.getSession().getAttribute("oldName"); System.out.println(name+" "+password+" "+eMail+" "+username); //更新数据库的信息 String sql = "update users set username=?,pwd=?,email=? where username=? "; Object[] objects = {name,password,eMail,username}; UserDao.userOperation(sql, objects); //提示信息 req.getSession().setAttribute("message", "已成功修改!"); //重定向 resp.sendRedirect(req.getContextPath()+"/updateInfo.jsp"); } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page language="java" import="com.lf.newhw.VerifyCode" %> <%@ page language="java" import="javax.imageio.ImageIO" %> <% 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 ‘image.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> <% //得到验证码并存入session String verifyCode = VerifyCode.getForthWord(); session.setAttribute("verifyCode", verifyCode); ImageIO.write(VerifyCode.productImage(verifyCode), "JPEG", response.getOutputStream()); /* System.out.println("ImageServlet...."+verifyCode); */ out.clear(); out = pageContext.pushBody(); %> </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> <h1>欢迎您,<%=session.getAttribute("username")%></h1> <a href="updateInfo.jsp">修改个人信息</a><br> <a href="info.jsp">查询所有用户</a> </body> </html>
<%@page import="com.lf.newhw.User"%> <%@page import="com.lf.newhw.jdbc.UserDao"%> <%@ 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 ‘info.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> <% List list = UserDao.requeryUsers(); //可继续完善(可以通过<table>显示,页面效果会好些) /* for(int i = 0;i < list.size();i++){ out.print(list.get(i)+"<br>"); } */ %> <table border="1"> <% //行 for(int i = 0;i < list.size();i++){ User user = (User)list.get(i); %> <tr> <% //每行3个单元格 for(int j = 0;j < 3;j++){ %> <td><%= j==0?user.getName():((j==1)?user.getPassword():user.getE_mail())%> <% } %> <br> <% } %> </table> </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 test</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"> --> <script> function changeVerifyCode(){ var time = new Date().getTime(); document.getElementById("img").src="image.jsp?"+time; } </script> </head> <body> <div> <form action="LoginServlet" method="post"> <% String msg = (String)request.getSession().getAttribute("msg"); msg = msg==null?"":msg; %> <h3><%=msg %></h3> <!-- 在此要进行回写(EL表达式) --> 用户名:<input type="text" name="username" value="${sessionScope.username}"/><br/> 密 码:<input type="text" name="password" value="${sessionScope.password}"/><br> <!-- 邮 箱:<input type="text" name="e-mail" /><br> --> 验证码:<input style="width:100px;" name="verifyCode"><img src="image.jsp" id="img"><u id="u" onclick="changeVerifyCode()">换一张</u> <br> <input type="submit" value="登录"/> </form> <button onclick="window.location.href=‘register.jsp‘">注册</button> </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 ‘register.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> <div> <h2>${sessionScope.tipMsg}</h2> <!--表单--> <form action="RegisterServlet" method="post"> <!--帐号--> <div class="row"> 用户名: <input type="text" placeholder=" 请输入帐号" name="rname" value="${sessionScope.rname}"/> </div> <!--密码--> <div class="row"> 密码:<input type="password" placeholder=" 请输入密码" name="rpassword" value="${sessionScope.rpassword}"/> </div> <!--确认密码--> <div > 确认密码:<input type="password" placeholder=" 请确认密码" name="rpwd" value="${sessionScope.rpwd}"/> </div> <!--邮箱--> <div> 邮箱:<input placeholder=" 请输入邮箱" name="remail" value="${sessionScope.remail}"/> </div> <!--提交按钮--> <div> <input type="submit" value="提交"/> </div> <a href="login.jsp">返回登录页面</a> </form> </div> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="com.lf.newhw.User"%> <% 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 ‘updateInfo.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> <form action="UpdateServlet" method="post"> <% User user = (User)session.getAttribute("user"); String oldName = user.getName(); session.setAttribute("oldName", oldName); String message = (String)session.getAttribute("message"); message = message==null?"":message; %> <h1>修改个人信息</h1> <h2><%= message%></h2> 用户名:<input type="text" name="updatename" value="<%=user.getName()%>"/><br/> 密 码:<input type="text" name="updatepwd" value="<%=user.getPassword()%>"/><br> 邮 箱:<input type="text" name="updateEmail" value="<%=user.getE_mail()%>"/><br> <input type="submit" value="提交"/><br> <a href="index.jsp">返回上一页</a> <br> </form> </body> </html>
<?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"> <!-- 注册LoginServlet --> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.lf.newhw.servlet.LoginServlet</servlet-class> </servlet> <!-- 配置LoginServlet映射 --> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <!-- 注册UpdateServlet --> <servlet> <servlet-name>UpdateServlet</servlet-name> <servlet-class>com.lf.newhw.servlet.UpdateServlet</servlet-class> </servlet> <!-- 配置UpdateServlet映射 --> <servlet-mapping> <servlet-name>UpdateServlet</servlet-name> <url-pattern>/UpdateServlet</url-pattern> </servlet-mapping> <!-- 注册UpdateServlet --> <servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>com.lf.newhw.servlet.RegisterServlet</servlet-class> </servlet> <!-- 配置UpdateServlet映射 --> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/RegisterServlet</url-pattern> </servlet-mapping> </web-app>
以上是关于JSP 登录与注册的小案例的主要内容,如果未能解决你的问题,请参考以下文章