Java组件javabean用户登录实例详解
本文简单讲述使用javabean实现用户登录,包括用户登录,注册和退出等。
1.关于javabean
JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性,set和get方法获取。众所周知,属性名称符合这种模式,其他Java 类可以通过自省机制发现和操作这些JavaBean 的属性。
2.系统架构
2.1登录用例图
2.2页面流程图
2.3系统架构图
2.4数据库设计
本例使用oracle数据库
用户表包括id,用户名,密码,email,共4个字段
-- Create table create table P_USER ( id VARCHAR2(50) not null, username VARCHAR2(20), password VARCHAR2(20), email VARCHAR2(50) ) tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64 minextents 1 maxextents unlimited ); -- Add comments to the table comment on table P_USER is '用户表'; -- Add comments to the columns comment on column P_USER.id is 'id'; comment on column P_USER.username is '用户名'; comment on column P_USER.password is '密码'; comment on column P_USER.email is 'email';
3.javabean编写
3.1开发数据库底层处理javabean
DBAcess.java
package com.baosight.bean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /**数据库操作类 * <p>Title:DBAcess </p> * <p>Description:TODO </p> * <p>Company: </p> * @author yuan * @date 2016-5-22 下午12:40:24*/ public class DBAcess { private String driver = "oracle.jdbc.driver.OracleDriver"; private String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:orcl"; private String username = "scott"; private String password = "tiger"; private Connection conn; private Statement stm; private ResultSet rs; //创建连接 public boolean createConn() { boolean b = false; try { Class.forName(driver);// 加载Oracle驱动程序 conn = DriverManager.getConnection(url, username, password); b = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }// 获取连接 catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } //修改 public boolean update(String sql){ boolean b = false; try { stm = conn.createStatement(); stm.execute(sql); b = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } //查询 public void query(String sql){ try { stm = conn.createStatement(); rs = stm.executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //判断有无数据 public boolean next(){ boolean b = false; try { if(rs.next()){ b = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } //获取表字段值 public String getValue(String field) { String value = null; try { if (rs != null) { value = rs.getString(field); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; } //关闭连接 public void closeConn() { try { if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //关闭statement public void closeStm() { try { if (stm != null) { stm.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //关闭ResultSet public void closeRs() { try { if (rs != null) { rs.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } 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 Statement getStm() { return stm; } public void setStm(Statement stm) { this.stm = stm; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public void setConn(Connection conn) { this.conn = conn; } public Connection getConn() { return conn; } }
上述数据库操作类使用JDBC连接数据库,并封装了连接数据库、查询、修改、关闭资源等方法。
3.2开发JavaBean业务逻辑组件
UserBean.java
package com.baosight.bean; import com.baosight.util.GenerateUUID; /** * <p>Title:UserBean </p> * <p>Description:TODO </p> * <p>Company: </p> * @author yuan * @date 2016-5-22 下午1:05:00*/ public class UserBean { //登录验证 public boolean valid(String username,String password){ boolean isValid = false; DBAcess db = new DBAcess(); if(db.createConn()){ String sql = "select * from p_user where username='"+username+"' and password='"+password+"'"; db.query(sql); if(db.next()){ isValid = true; } db.closeRs(); db.closeStm(); db.closeConn(); } return isValid; } //注册验证 public boolean isExist(String username){ boolean isValid = false; DBAcess db = new DBAcess(); if(db.createConn()){ String sql = "select * from p_user where username='"+username+"'"; db.query(sql); if(db.next()){ isValid = true; } db.closeRs(); db.closeStm(); db.closeConn(); } return isValid; } //注册用户 public boolean add(String username,String password,String email){ boolean isValid = false; DBAcess db = new DBAcess(); if(db.createConn()){ String sql = "insert into p_user(id,username,password,email) values('"+GenerateUUID.next()+"','"+username+"','"+password+"','"+email+"')"; isValid = db.update(sql); db.closeStm(); db.closeConn(); } return isValid; } }
上述业务逻辑javabean,定义了登录验证、注册验证和新增用户等方法
3.3关于生成唯一ID
上面在新增用户时需要插入ID,本例使用UUID来生成唯一ID
GenerateUUID.java
package com.baosight.util; import java.util.Date; /** * <p>Title:GenerateUUID </p> * <p>Description:TODO </p> * <p>Company: </p> * @author yuan * @date 2016-5-22 下午1:31:46*/ public class GenerateUUID { private static Date date = new Date(); // private static StringBuilder buf = new StringBuilder(); private static int seq = 0; private static final int ROTATION = 99999; public static synchronized long next(){ if (seq > ROTATION) seq = 0; // buf.delete(0, buf.length()); date.setTime(System.currentTimeMillis()); String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++); return Long.parseLong(str); } public static void main(String[] args) { for(int i=0;i<100;i++){ System.out.println(next()); } } }
4.页面编写
4.1登录页面
login.jsp
<%@ 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>登录页面</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="login_action.jsp" method="post"> <table> <tr> <td colspan="2">登录窗口</td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="username" /> </td> </tr> <tr> <td>密码:</td> <td><input type="text" name="password" /> </td> </tr> <tr> <td colspan="2"><input type="submit" value="登录" /> <a href="register.jsp">注册</a> </td> </tr> </table> </form> </body> </html>
页面效果
4.2登录业务逻辑处理页面
login_action.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page import="java.sql.*" %> <%@ page import="com.baosight.bean.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% String username = request.getParameter("username"); String password = request.getParameter("password"); if(username==null||"".equals(username.trim())||password==null||"".equals(password.trim())){ //out.write("用户名或密码不能为空!"); System.out.println("用户名或密码不能为空!"); response.sendRedirect("login.jsp"); return; //request.getRequestDispatcher("login.jsp").forward(request, response); } UserBean userBean = new UserBean(); boolean isValid = userBean.valid(username,password); if(isValid){ System.out.println("登录成功!"); session.setAttribute("username", username); response.sendRedirect("welcome.jsp"); return; }else{ System.out.println("用户名或密码错误,登录失败!"); response.sendRedirect("login.jsp"); return; } %>
上面的JSP调用了Javabean进行业务处理
当用户名或密码为空时返回登录页面login.jsp
当登录成功后将用户信息保存到session,跳转到欢迎页面welcome.jsp
当登录失败时返回登录页面login.jsp
4.3登录成功欢迎页面
welcome.jsp
<%@ 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 'welcom.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> <table> <tr> <td><img src="images/logo4.png" /> </td> <td><img src="images/logo2.png" height="90" /> </td> </tr> <tr> <td colspan="2"><hr /> </td> </tr> <tr> <td> <table> <tr> <td><a>Main</a> </td> </tr> <tr> <td><a>Menu1</a> </td> </tr> <tr> <td><a>Menu2</a> </td> </tr> <tr> <td><a>Menu3</a> </td> </tr> <tr> <td><a>Menu4</a> </td> </tr> <tr> <td><a>Menu5</a> </td> </tr> <tr> <td><a>Menu6</a> </td> </tr> <tr> <td><a>Menu7</a> </td> </tr> <tr> <td><a>Menu8</a> </td> </tr> </table></td> <td> <form action="loginout.jsp" method="post"> <table> <tr> <td colspan="2">登录成功!</td> </tr> <tr> <td>欢迎你,</td> <td>${username }</td> </tr> <tr> <td colspan="2"><input type="submit" value="退出" /></td> </tr> </table> </form></td> </tr> </table> </body> </html>
页面效果
4.4退出登录业务处理页面
loginout.jsp
<%@ 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 'loginout.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.removeAttribute("username"); response.sendRedirect("login.jsp"); %> </body> </html>
从session中移除用户信息,跳转到登录页面login.jsp
4.5用户注册页面
register.jsp
<%@ 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>注册页面</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="register_action.jsp" method="post"> <table> <tr> <td colspan="2">注册窗口</td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>密码:</td> <td><input type="text" name="password1" /></td> </tr> <tr> <td>确认密码:</td> <td><input type="text" name="password2" /></td> </tr> <tr> <td>email:</td> <td><input type="text" name="email" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="注册" /> <a href="login.jsp">返回</a></td> </tr> </table> </form> </body> </html>
运行效果
4.6注册业务处理页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="com.baosight.bean.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% String username = request.getParameter("username"); String password1 = request.getParameter("password1"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); if(username==null||"".equals(username.trim())||password1==null||"".equals(password1.trim())||password2==null||"".equals(password2.trim())||!password1.equals(password2)){ //out.write("用户名或密码不能为空!"); System.out.println("用户名或密码不能为空!"); response.sendRedirect("register.jsp"); return; //request.getRequestDispatcher("login.jsp").forward(request, response); } UserBean userBean = new UserBean(); boolean isExit = userBean.isExist(username); if(!isExit){ userBean.add(username, password1, email); System.out.println("注册成功,请登录!"); response.sendRedirect("login.jsp"); return; }else{ System.out.println("用户名已存在!"); response.sendRedirect("register.jsp"); return; } %>
上面的JSP调用了Javabean进行业务处理
当用户名或密码为空时返回注册页面register.jsp
当注册用户名在数据库不存在时,新增用户
新增成功后跳转到登录页面login.jsp
当注册用户名在数据库存在时,返回注册页面register.jsp
5.总结
本例使用javabean对数据库操作和业务逻辑处理进行了封装。
以上即为使用javabean实现用户登录的简单介绍,还需要不断完善,希望大家一起学习进步!