JavaBean实现用户登陆

本文简单讲述使用javabean实现用户登录,包括用户登录,注册和退出等。

  1. 系统结构图

  2.数据库表

  1. create table P_USER  
  2. (  
  3.   id       VARCHAR2(50) not null,  
  4.   username VARCHAR2(20),  
  5. password VARCHAR2(20),  
  6.   email    VARCHAR2(50)  

  3.JavaBean编写

DataAccess.java   数据库操作类使用JDBC连接数据库,并封装了连接数据库、查询、修改、关闭资源等方法

  1 package data;
  2 import java.sql.Connection;
  3 import java.sql.DriverManager;
  4 import java.sql.ResultSet;
  5 import java.sql.SQLException;
  6 import java.sql.Statement;
  7 
  8 public class DataAccess {
  9       private String driver="oracle.jdbc.driver.OracleDriver";
 10       private String url="jdbc:oracle:" + "thin:@localhost:1521:orcl";
 11       private String username="C##LYJ";
 12       private String password="lyj123123";
 13       private Connection con;
 14       private Statement stm=null;
 15       private ResultSet rs;
 16       
 17       public String getDriver(){
 18           return driver;
 19       }
 20       public void setDriver(String driver){
 21           this.driver=driver;
 22       }
 23       
 24       public String getUrl(){
 25           return url;
 26       }
 27       public void setUrl(String url){
 28           this.url=url;
 29       }
 30       
 31       public String getUsername(){
 32           return username;
 33       }
 34       public void steUsername(String username){
 35           this.username=username;
 36       }
 37       
 38       public String getPassword(){
 39           return password;
 40       }
 41       public void setPassword(String password){
 42           this.password=password;
 43       }
 44       
 45       public Connection getCon(){
 46           return con;
 47       }
 48       public void steCon(Connection con){
 49           this.con=con;
 50       }
 51       
 52       public Statement getStm(){
 53           return stm;
 54       }
 55       public void setStm(Statement stm){
 56           this.stm=stm;
 57       }
 58       
 59       public ResultSet getRs(){
 60           return rs;
 61       }
 62       public void setRs(ResultSet rs){
 63           this.rs=rs;
 64       }
 65       //创建连接
 66       public boolean creatCon(){
 67           boolean b=false;
 68           try{
 69               Class.forName(driver);//加载oracle驱动程序
 70               con=DriverManager.getConnection(url, username, password);
 71               b=true;
 72           }catch(SQLException e){
 73               e.printStackTrace();
 74           }
 75           catch(ClassNotFoundException e){
 76               e.printStackTrace();
 77           }
 78           return b;
 79       }
 80       //修改
 81       public boolean update(String sql){
 82           boolean b=false;
 83           try{
 84               stm=this.con.createStatement();
 85               stm.execute(sql);
 86               b=true;
 87           }catch(SQLException e){
 88               e.printStackTrace();
 89           }
 90               return b;                        
 91       }
 92       //查询
 93       public void query(String sql){
 94           try{
 95               stm=con.createStatement();
 96               rs=stm.executeQuery(sql);
 97           }
 98           catch(SQLException e){
 99               e.getSQLState();
100           }
101       }
102       
103       //判断有无数据
104       public boolean next(){
105           boolean b=false;
106           try{
107               if(rs.next()){
108                   b=true;
109               }
110           }catch(SQLException e){
111               e.printStackTrace();
112           }
113           return b;
114       }
115       //获取表字段值
116       public String getValue(String field){
117           String value=null;
118           try{
119               if(rs!=null){
120                   value=rs.getString(field);
121               }
122           }catch(SQLException e){
123               e.printStackTrace();
124           }
125           return value;
126       }
127       
128       //关闭连接
129       public void closeCon(){
130           try{
131               if(con!=null){
132                   con.close();
133               }
134           }catch(SQLException e){
135               e.printStackTrace();
136           }
137       }
138       
139       //关闭Statement
140       public void closeStm(){
141           try{
142               if(stm!=null){
143                   stm.close();
144               }
145           }catch(SQLException e){
146               e.printStackTrace();
147           }
148       }
149       
150       //关闭ResultSet
151       public void closeRs(){
152           try{
153               if(rs!=null){
154                   rs.close();
155               }
156           }catch(SQLException e){
157               e.printStackTrace();
158           }
159       }
160       
161 }

UserBean.java   对数据库的增加、查询,即定义了登录验证、注册验证和新增用户等方法

 1 package data;
 2 
 3 public class UserBean {
 4     //登陆验证
 5     public boolean valid(String username,String password){
 6         boolean isValid=false;
 7         DataAccess db=new DataAccess();
 8         if(db.creatCon()){
 9             String sql="select * from p_user where us='"+username+"' and ps='"+password+"'";
10             db.query(sql);
11             if(db.next()){
12                 isValid=true;
13                 System.out.print("成功!");
14             }
15             db.closeRs();
16             db.closeStm();
17             db.closeCon();
18         }
19         return isValid;
20     }
21     
22     //注册验证
23     public boolean isExist(String username){
24         boolean isValid=false;
25         DataAccess db=new DataAccess();
26         if(db.creatCon()){
27             String sql="select * from p_user where us='"+username+"'";  
28             db.query(sql);
29             if(db.next()){
30                 isValid=true;
31             }
32             db.closeRs();
33             db.closeStm();
34             db.closeCon();
35         }
36         return isValid;
37     }
38     //注册用户
39     public boolean add(String username,String password,String email){
40         boolean isValid=false;
41         DataAccess db=new DataAccess();
42         if(db.creatCon()){
43             String sql= "insert into p_user(id,us,ps,email) values('"+GenerateUnID.next()+"','"+username+"','"+password+"','"+email+"')";  
44             isValid=db.update(sql);
45             db.closeRs();
46             db.closeStm();
47             db.closeCon();
48         }
49         return isValid;
50     }
51 }

 

GenerateUnID.java  为每个用户生成唯一ID

 1 package data;
 2 import java.util.Date;
 3 
 4 public class GenerateUnID {
 5       private static Date date=new Date();
 6       private static int seq=0;
 7       private static final int ROTATION=99999;
 8       public static synchronized long next(){
 9           if(seq>ROTATION) seq=0;
10           date.setTime(System.currentTimeMillis());
11           String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++);
12           return Long.parseLong(str);
13       }
14       public static void main(String[] args){
15           for(int i=0;i<100;i++){
16               System.out.println(next());
17           }
18       } 
19       
20 }

  4.JSP页面编写

    4.1 登陆页面  login.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24      <form action="login_action.jsp" method="post">
25            <table>
26                <tr>
27                    <td colspan="2">登陆窗口</td>
28                </tr>
29                <tr>
30                    <td>用户名:</td>
31                    <td><input type="text" name="username"/></td>
32                </tr>
33                <tr>
34                    <td>密    码:</td>
35                    <td><input type="password" name="password"/></td>
36                </tr>
37                <tr>
38                    <td colspan="2"><input type="submit" value="登陆"/><a href="register.jsp">注册</a></td>
39                </tr>
40            </table>
41    </form>
42   </body>
43 </html>

    4.2 登陆页面逻辑处理  login_action.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'login_action.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <%@ page import="data.*" %>
27     <%@ page import="java.sql.*" %>
28   
29    <%
30            String us=request.getParameter("username");
31            String ps=request.getParameter("password");
32            if(us==null||"".equals(us.trim())||ps==null||"".equals(ps.trim())){
33                System.out.print("用户名或者密码不能为空!");
34                response.sendRedirect("index.jsp");
35                
36            }
37          
38            UserBean userBean=new UserBean();
39            boolean isValid=userBean.valid(us, ps);
40            System.out.print(isValid);
41            if(isValid){
42                System.out.println("登陆成功!");
43                session.setAttribute("username", us);
44                response.sendRedirect("welcom.jsp");
45            }
46            else{
47                System.out.print("用户名或者密码错误!");
48                response.sendRedirect("login.jsp");
49            }
50            
51     %>
52   </body>
53 </html>

    4.3 登陆欢迎界面 welcom.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'welcom.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <form action="loginout.jsp" method="post">
27         <table>
28             <tr>
29                 <td colspan="2">登陆成功</td>
30             </tr>
31             <tr>
32                 <td>欢迎你:</td>
33                 <td><%=session.getAttribute("username")%></td>
34             </tr>
35             <tr>
36                 <td colspan="2"><input type="submit" value="退出"/></td>
37             </tr>
38         </table>
39     </form>
40   </body>
41 </html>

    4.4  用户注册页面 register.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'register.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <form action="register_action.jsp" method="post">
27         <table>
28             <tr>
29                 <td colspan="2">窗口注册</td>
30             </tr>
31             <tr>
32                 <td>用户名:</td>
33                 <td><input type="text" name="username"></td>
34             </tr>
35             <tr>
36                 <td>密       码:</td>
37                 <td><input type="password" name="password1"></td>
38             </tr>
39             <tr>
40                 <td>确认密码:</td>
41                 <td><input type="password" name="password2"></td>
42             </tr>
43             <tr>
44                 <td>email:</td>
45                 <td><input type="text" name="email"></td>
46             </tr>
47             <tr>
48                 <td colspan="2"><input type="submit" value="注册"><a href="login.jsp">返回</a></td>
49             </tr>
50         </table>
51     </form>
52   </body>
53 </html>

    4.4 注册页面逻辑处理 register_action.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <%@ page import="data.*" %>
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'register_action.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26       
27       <%
28           String username=request.getParameter("username");
29           String password1=request.getParameter("password1");
30           String password2=request.getParameter("password2");
31           String email=request.getParameter("email");
32           if(username==null||"".equals(username.trim())||password1==null
33           ||"".equals(password1)||password2==null||"".equals(password2)||!password1.equals(password2)){
34               System.out.print("用户名或密码不能为空!");
35               response.sendRedirect("register.jsp");
36               return;
37           }
38           UserBean userbean=new UserBean();
39           boolean isExit=userbean.isExist(username);
40           if(!isExit){
41               userbean.add(username, password1, email);
42               System.out.print("注册成功,请登陆!");
43               response.sendRedirect("login.jsp");
44               
45           }
46           else{
47               System.out.print("用户名已存在!");
48               response.sendRedirect("register.jsp");
49               
50           }
51        %>
52   </body>
53 </html>

    4.5  退出页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'loginout.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <%
27         session.removeAttribute("username");
28         response.sendRedirect("login.jsp");
29      %>
30   </body>
31 </html>

    5. 总结

      主要是为了使用javabean对数据库操作和业务逻辑处理进行了封装,例子很简单,由小及大,掌握思想即可。

源码:https://github.com/lyj8330328/JavaBean

原文地址:https://www.cnblogs.com/lyj-gyq/p/8524652.html