This article briefly describes the use of javabean to realize user login, including user login, registration and logout.
1. About javabean
JavaBean is a reusable component written in the JAVA language. To be written as a JavaBean, the class must be specific and public, and has a parameterless constructor. JavaBeans expose internal domains to member properties, set and get methods by providing public methods that conform to the consistent design pattern. As we all know, attribute names conform to this pattern, and other Java classes can discover and manipulate the properties of these JavaBeans through introspection mechanisms.
2. System architecture
2.1 Login use case diagram
2.2 Page flowchart
2.3 System Architecture Diagram
2.4 Database Design
This example uses an oracle database
The user table includes id, username, password, email, and a total of 4 fields.
-- 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 'user table'; -- Add comments to the columns comment on column P_USER.id is 'id'; comment on column P_USER.username is 'username'; comment on column P_USER.password is 'password'; comment on column P_USER.email is 'email';
3. Javabean writing
3.1 Developing the underlying database processing of javabeans
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; /**Database operation class* <p>Title:DBAcess </p> * <p>Description:TODO </p> * <p>Company: </p> * @author yuan * @date 2016-5-22 12:40:24 pm*/ 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; //Create connection public boolean createConn() { boolean b = false; try { Class.forName(driver);//Load Oracle driver conn = DriverManager.getConnection(url, username, password); b = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }// Get the connection catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } // Modify 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; } //Query public void query(String sql){ try { stm = conn.createStatement(); rs = stm.executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Judge whether there is data public boolean next(){ boolean b = false; try { if(rs.next()){ b = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } //Get the table field value 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; } //Close the connection public void closeConn() { try { if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Close statement public void closeStm() { try { if (stm != null) { stm.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Close 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; } }The above database operation class uses JDBC to connect to the database and encapsulates methods such as connecting to the database, querying, modifying, and closing resources.
3.2 Develop JavaBean business logic components
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 pm*/ public class UserBean { //Login verification 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; } //Register verification 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; } //Register user 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; } }The above business logic javabean defines methods such as login verification, registration verification and new users
3.3 About Generating a Unique ID
The above needs to insert an ID when adding a new user. In this example, UUID is used to generate a unique 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 pm*/ 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 = 9999; 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. Page writing
4.1 Login page
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>Login 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="login_action.jsp" method="post"> <table> <tr> <td colspan="2">Login window</td> </tr> <tr> <td>Username: </td> <td><input type="text" name="username" /> </td> </tr> <tr> <td>Password: </td> <td><input type="text" name="password" /> </td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" /> <a href="register.jsp">Register</a> </td> </tr> </table> </form> </body> </html>
Page Effect
4.2 Log in to the business logic processing page
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("username or password cannot be empty!"); System.out.println("username or password cannot be empty!"); 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("Login successfully!"); session.setAttribute("username", username); response.sendRedirect("welcome.jsp"); return; }else{ System.out.println("Unknown username or password, login failed!"); response.sendRedirect("login.jsp"); return; } %>The above JSP calls Javabean for business processing. Return to the login page when the username or password is empty.
When the login is successful, save the user information to the session and jump to the welcome page welcome.jsp
Return to login page when login fails login.jsp
4.3 Login successfully welcome page
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> <tr> <td><img src="images/logo4.png" /> </td> <td><img src="images/logo2.png" /> </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>Menu7</a> </td> </tr> <tr> <td><a>Menu8</a> </td> </tr> </tr> </tr> </tr> </tr> </tr> </tr> </tr> </tr> <td> <form action="loginout.jsp" method="post"> <table> <tr> <td colspan="2">Login successfully!</td> </tr> <tr> <td>Welcome, </td> <td>${username }</td> </tr> <tr> <td>Welcome, </td> <tr>${username }</td> </tr> <tr> <td> colspan="2"><input type="submit" value="Exit" /></td> </tr> </table> </form></td> </tr> </tr> </table> </body> </html>Page Effect
4.4 Log out of the business processing page
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>Remove user information from session and jump to login page login.jsp
4.5 User Registration Page
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>Register 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="register_action.jsp" method="post"> <table> <tr> <td colspan="2">Register window</td> </tr> <tr> <td>Username: </td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password: </td> <td><input type="text" name="password1" /></td> </tr> <tr> <td>Confirm password: </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="register" /> <a href="login.jsp">Return</a></td> </tr> </table> </form> </body> </html>
Running effect
4.6 Registration business processing page
<%@ 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("Username or password cannot be empty!"); System.out.println("Username or password cannot be empty!"); 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("Registered successfully, please log in! "); response.sendRedirect("login.jsp"); return; }else{ System.out.println("Username already exists!"); response.sendRedirect("register.jsp"); return; } %>The above JSP calls Javabean for business processing
Return to the registration page when the username or password is empty register.jsp
When the registered username does not exist in the database, new users are added
After the new addition is successful, jump to the login page login.jsp
When the registered username exists in the database, return to the registration page register.jsp
5. Summary
This example uses javabean to encapsulate database operations and business logic processing.
The above is a brief introduction to using javabean to realize user login, and it needs to be continuously improved. I hope everyone can learn and make progress together!