Jsp+Servlet+JavaBean+JDBC登陸實例

運行環境:                                                                                         網易博客cyeagle
引用
JDK1.5
Tomcat5.5
MyEclips5.5.1 GA
SqlServer2000
windows2003


1.在SqlServer下的查詢分析器中新建表:
Sql代碼  收藏代碼
  1. create table dbuser(  
  2. userId int identity(1,1) primary key not null,  
  3. userName varchar(50),  
  4. userPasswd varchar(50))  


2.在MyEclipse中新建Web工程,並創建包結構。




3.編寫登陸界面。
Html代碼  收藏代碼
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
  7. <title>Insert title here</title>  
  8. <style type="text/css">  
  9. body{  
  10.  color : #000 ;  
  11.  font-size : 12px ;  
  12.   
  13.  margin : 0px auto ;  
  14.  }  
  15.   
  16. </style>  
  17.   
  18. <script type="text/javascript">  
  19.     function check(form){  
  20.     //document.forms.form1.username.value取得form1中Username的值 並判斷是否爲空  
  21.         if(document.forms.form1.username.value==""){  
  22.         //如果 爲""則彈出提示  
  23.             alert("pls input username");  
  24.             //將輸入焦點定位到沒有輸入的地方  
  25.             document.forms.form1.username.focus();  
  26.             //返回錯誤  
  27.             return false;  
  28.         }  
  29.                 if(document.forms.form1.password.value==""){  
  30.             alert("pls input password");  
  31.             document.forms.form1.password.focus();  
  32.             return false;  
  33.         }  
  34.     }  
  35.   
  36. </script>  
  37. </head>  
  38. <body>  
  39. <form action="LoginServlet" method="post" name="form1">  
  40.       
  41.       
  42. <table border="1" cellspacing="1" cellpadding="1"  bordercolor="silver" align="center">  
  43.    <tr>  
  44.       <td colspan="2" align="center" bgcolor="#e8e8e8">用戶登陸</td>  
  45.    </tr>  
  46.    <tr>  
  47.       <td>用戶名:</td>  
  48.       <td><input type="text" name="username"/></td>  
  49.    </tr>  
  50.    <tr>  
  51.       <td>密碼:</td>  
  52.       <td><input type="password" name="password"/></td>  
  53.    </tr>  
  54.    <tr>  
  55.       <td><a href="rsg.jsp" >新用戶註冊</a></td>  
  56.       <!-- οnclick="return check(this) 調用上面的Script進行驗證 -->  
  57.       <td><input type="submit" name="submit" onclick="return check(this);"/><input type="reset" name="reset"/></td>  
  58.    </tr>  
  59. </table>  
  60.   
  61. </form>  
  62. </body>  
  63. </html>  




3.編寫工具類DBConn。
Java代碼  收藏代碼
  1. package utils;  
  2.   
  3.     import java.io.*;     
  4. import java.sql.*;     
  5.   
  6. public class DBConn {     
  7.         public static String driver;//定義驅動     
  8.         public static String url;//定義URL     
  9.         public static String user;//定義用戶名     
  10.         public static String password;//定義密碼     
  11.         public static Connection conn;//定義連接     
  12.         public static Statement stmt;//定義STMT     
  13.         public ResultSet rs;//定義結果集     
  14.         //設置CONN     
  15.         static{     
  16.             try {   
  17.                 driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";  
  18.                 url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=qtliu";  
  19.                 user="sa";  
  20.                 password="sa";  
  21.                 Class.forName(driver);     
  22.                 conn = DriverManager.getConnection(url,user,password);  
  23.                 System.out.println("-------連接成功------");  
  24.             } catch(ClassNotFoundException classnotfoundexception) {     
  25.                   classnotfoundexception.printStackTrace();     
  26.                 System.err.println("db: " + classnotfoundexception.getMessage());     
  27.             } catch(SQLException sqlexception) {     
  28.                 System.err.println("db.getconn(): " + sqlexception.getMessage());     
  29.             }     
  30.         }     
  31.         //構造函數,默認加裁配置文件爲jdbc.driver     
  32.         public DBConn(){     
  33.             this.conn=this.getConn();  
  34.         }     
  35.         //返回Conn     
  36.         public Connection getConn(){     
  37.             return this.conn;     
  38.         }     
  39.         //執行插入     
  40.            public void doInsert(String sql) {     
  41.             try {     
  42.                 stmt = conn.createStatement();     
  43.                 int i = stmt.executeUpdate(sql);     
  44.             } catch(SQLException sqlexception) {     
  45.                 System.err.println("db.executeInset:" + sqlexception.getMessage());     
  46.             }finally{     
  47.                      
  48.             }     
  49.         }     
  50.         //執行刪除     
  51.         public void doDelete(String sql) {     
  52.             try {     
  53.                 stmt = conn.createStatement();     
  54.                 int i = stmt.executeUpdate(sql);     
  55.             } catch(SQLException sqlexception) {     
  56.                 System.err.println("db.executeDelete:" + sqlexception.getMessage());     
  57.             }     
  58.         }     
  59.         //執行更新     
  60.         public void doUpdate(String sql) {     
  61.             try {     
  62.                 stmt = conn.createStatement();     
  63.                 int i = stmt.executeUpdate(sql);     
  64.             } catch(SQLException sqlexception) {     
  65.                 System.err.println("db.executeUpdate:" + sqlexception.getMessage());     
  66.             }     
  67.         }     
  68.         //查詢結果集     
  69.         public ResultSet doSelect(String sql) {     
  70.             try {  
  71.                 conn=DriverManager.getConnection(url,user,password);  
  72.                 stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);       
  73.                 rs = stmt.executeQuery(sql);   
  74.                 System.out.println("取得結果集");  
  75.             } catch(SQLException sqlexception) {     
  76.                 System.err.println("db.executeQuery: " + sqlexception.getMessage());     
  77.             }     
  78.             return rs;     
  79.         }     
  80.         /**   
  81.          *關閉數據庫結果集,數據庫操作對象,數據庫鏈接   
  82.            @Function: Close all the statement and conn int this instance and close the parameter ResultSet   
  83.            @Param: ResultSet   
  84.            @Exception: SQLException,Exception   
  85.           **/    
  86.          public void close(ResultSet rs) throws SQLException, Exception {     
  87.         
  88.            if (rs != null) {     
  89.              rs.close();     
  90.              rs = null;     
  91.            }     
  92.         
  93.            if (stmt != null) {     
  94.              stmt.close();     
  95.              stmt = null;     
  96.            }     
  97.         
  98.            if (conn != null) {     
  99.              conn.close();     
  100.              conn = null;     
  101.            }     
  102.          }     
  103.         
  104.          /**   
  105.           *關閉數據庫操作對象,數據庫連接對象   
  106.           * Close all the statement and conn int this instance   
  107.           * @throws SQLException   
  108.           * @throws Exception   
  109.           */    
  110.          public void close() throws SQLException, Exception {     
  111.            if (stmt != null) {     
  112.              stmt.close();     
  113.              stmt = null;     
  114.            }     
  115.         
  116.            if (conn != null) {     
  117.              conn.close();     
  118.              conn = null;     
  119.            }     
  120.          }     
  121.         //測試類     
  122. //       public static void main(String []args){  
  123. //           DBConn db=new DBConn();  
  124. //           db.getConn();  
  125. //          ResultSet rs=db.doSelect("select * from db_user where userName='admin'");  
  126. //          try {  
  127. //              while(rs.next()){  
  128. //                  System.out.println(rs.getInt(1));  
  129. //                  System.out.println(rs.getString(3));  
  130. //                    
  131. //              }  
  132. //          } catch (SQLException e) {  
  133. //              // TODO Auto-generated catch block  
  134. //              e.printStackTrace();  
  135. //          }  
  136. //       }  
  137.     }    


4.編寫Servlet,LoginServlet.java。
Java代碼  收藏代碼
  1. package servlet;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.RequestDispatcher;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import model.CheckUser;  
  12. import beans.UserBean;  
  13.   
  14. public class LoginServlet extends HttpServlet {  
  15.   
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 7381169134016556647L;  
  20.   
  21.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.             doPost(request,response);  
  24.     }  
  25.   
  26.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.         //設置HTTP響應的文檔類型,此處爲Text/html,如果更改爲application\msword則設置爲word文檔格式  
  29.         response.setContentType("text/html");  
  30.         //設置響應所採用的編碼方式  
  31.         response.setCharacterEncoding("GB18030");  
  32.         //取得參數username的值  
  33.         String uname=request.getParameter("username");  
  34.         String passwd=request.getParameter("password");  
  35.           
  36.           
  37.         UserBean user=new UserBean();  
  38.         user.setUsername(uname);  
  39.         user.setPassword(passwd);  
  40.         CheckUser cku=new CheckUser();  
  41.         boolean bool=cku.checkUsre(user);  
  42.           
  43.         String forward;  
  44.         if(bool){  
  45.             forward="success.jsp";  
  46.               
  47.         }else{  
  48.             forward="error.jsp";  
  49.         }  
  50.         RequestDispatcher rd=request.getRequestDispatcher(forward);  
  51.         rd.forward(request,response);  
  52.     }  
  53.   
  54.   
  55. }  

5.在web.xml中配置Servlet。
引用

配置關鍵代碼
Xml代碼  收藏代碼
  1. <servlet>  
  2.    <servlet-name>LoginServlet</servlet-name>  
  3.    <servlet-class>servlet.LoginServlet</servlet-class>  
  4.  </servlet>  
  5.   
  6.  <servlet-mapping>  
  7.    <servlet-name>LoginServlet</servlet-name>  
  8.    <url-pattern>/LoginServlet</url-pattern>  
  9.  </servlet-mapping>  


本機上的整個Web.xml代碼
Xml代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <servlet>  
  8.     <servlet-name>LoginServlet</servlet-name>  
  9.     <servlet-class>servlet.LoginServlet</servlet-class>  
  10.   </servlet>  
  11.   
  12.   <servlet-mapping>  
  13.     <servlet-name>LoginServlet</servlet-name>  
  14.     <url-pattern>/LoginServlet</url-pattern>  
  15.   </servlet-mapping>  
  16.   <welcome-file-list>  
  17.     <welcome-file>index.jsp</welcome-file>  
  18.   </welcome-file-list>  
  19. </web-app>  




5.編寫userBean。
Java代碼  收藏代碼
  1. package beans;  
  2.   
  3. public class UserBean {  
  4.       
  5.   
  6.     public String username;  
  7.     public String password;  
  8.       
  9.     public UserBean() {  
  10.         super();  
  11.     }  
  12.       
  13.       
  14.     public String getPassword() {  
  15.         return password;  
  16.     }  
  17.     public void setPassword(String password) {  
  18.         this.password = password;  
  19.     }  
  20.     public String getUsername() {  
  21.         return username;  
  22.     }  
  23.     public void setUsername(String username) {  
  24.         this.username = username;  
  25.     }  
  26.   
  27. }  


6.編寫JavaBean CheckUser。
Java代碼  收藏代碼
  1. package model;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5.   
  6. import utils.DBConn;  
  7. import utils.DBUtils;  
  8. import beans.UserBean;  
  9.   
  10. public class CheckUser {  
  11.       
  12.     public boolean checkUsre(UserBean user){  
  13.         if(user.username.equals("")||user.username!=null){  
  14.             ResultSet rs=null;  
  15.             DBConn db=new DBConn();  
  16.             rs=db.doSelect("select * from db_user where userName='"+user.getUsername()+"'");  
  17.             try {  
  18.                 if(rs.next()){  
  19.                     if(user.password.equals("")||user.password!=null){  
  20.                         rs=db.doSelect("select * from db_user where userPasswd="+user.password);  
  21.                         return true;  
  22.                     }  
  23.                 }  
  24.             } catch (SQLException e) {  
  25.                 e.printStackTrace();  
  26.             }  
  27.         }  
  28.           
  29.         return false;  
  30.           
  31.     }  
  32.   
  33. }  


7.編寫錯誤頁面及成功登陸頁面。

error.jsp
Jsp代碼  收藏代碼
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10. Sorry!你的登陸信息不正確!系統無法讓你登陸!<a href="login.jsp">點擊返回</a>  
  11. </body>  
  12. </html>  


success.jsp
Jsp代碼  收藏代碼
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>  
  3.   
  4. <jsp:useBean id="user" class="beans.UserBean" scope="request"/>  
  5. <jsp:setProperty name="user" property="*"/>  
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
  10. <title>Insert title here</title>  
  11. </head>  
  12. <body>  
  13. <%   
  14.     session.setAttribute("user",user);  
  15.     String username=user.getUsername();  
  16.  %>  
  17.    
  18.  <%=username %>,歡迎您來到FUCK網!<br>  
  19.  您的IP是:<%=request.getRemoteAddr() %><br>  
  20. 你的主機是:<%=request.getRemoteHost() %><br>  
  21. 你使用的協議是:<%=request.getProtocol() %><br>  
  22. 你目前的地址是:<%=request.getRealPath("/") %>  
  23. 你的主機端口是:<%=request.getRemotePort() %>  
  24. </body>  
  25. </html>  


=====================================================================
頁面流向圖





所涉知識點:
*JDBC連接的數據庫的寫法

*在Web.xml中配置Servlet




*在JSP中使用JavaBean


<jsp:useBean>與<jsp:setProperty>
<jsp:useBean>與<jsp:setProperty>是聯繫在一起的,在<jsp:setProperty>中的name值應當和<jsp:useBean>中的ID值相同。

Jap代碼  收藏代碼
  1. <jsp:useBean id="user" class="beans.UserBean" scope="request"/>  
  2. <jsp:setProperty name="user" property="*"/>  


*js驗證的寫法,及在頁面中的觸發
Javascript代碼  收藏代碼
  1. <script type="text/javascript">  
  2.     function check(form){  
  3.         if(document.forms.form1.username.value==""){  
  4.             alert("pls input username");  
  5.             document.forms.form1.username.focus();  
  6.             return false;  
  7.         }  
  8.                 if(document.forms.form1.password.value==""){  
  9.             alert("pls input password");  
  10.             document.forms.form1.password.focus();  
  11.             return false;  
  12.         }  
  13.     }  
  14.   
  15. </script>  
  16.   
  17. <input type="submit" name="submit" οnclick="return check(this);"/>  


*request、response的常見用法


Java代碼  收藏代碼
  1. request常用方法  
  2.   
  3. 取得相關信息:  
  4. 您的IP是:<%=request.getRemoteAddr() %><br>  
  5. 你的主機是:<%=request.getRemoteHost() %><br>  
  6. 你使用的協議是:<%=request.getProtocol() %><br>  
  7. 你目前的地址是:<%=request.getRealPath("/") %>  
  8.   
  9. 接收請求內容:  
  10.   
  11. 通過:Request.getParemeter(“username”) 接收請求內容:代碼如下所示:  
  12. String name = request.getParameter("uname") ;  
  13. 取得文本框提交的信息  
  14. String name = request.getParameter("uname") ;  
  15. 取得按鈕的名字:  
  16. String name = request.getParameter("submit") ;  
  17.   
  18. 設置瀏覽器的輸出文件類型,及編碼標準  
  19. <%@page contentType="text/html;charset=gb2312"%>  
  20.   
  21. 兩秒後自動跳轉到新頁面:  
  22. <%response.setHeader("refresh","3;URL=login.jsp");%>  
  23.   
  24. //設置HTTP響應的文檔類型,此處爲Text/html,如果更改爲application\msword則設置爲word文檔格式  
  25.   
  26. response.setContentType("text/html");  
  27.   
  28. //設置響應所採用的編碼方式  
  29. response.setCharacterEncoding("GB18030");  


*轉發和重定向的區別

轉向頁面:
重定向(redirect):以前的request中存放的變量全部失效,並進入一個新的request作用域。
轉發(Forward):以前的request中存放的變量不會失效,就像把兩個頁面拼到了一起。
<jsp:forward page="login_success.jsp"/>
(注:只要使用了服務器端跳轉<jsp:forward>,則請求內容可以在跳轉之後的頁面繼續得到)
Java代碼  收藏代碼
  1. Response.sendRedirect(“URL”);//重定向  
  2.   
  3. request.getRequestDispatcher("apage.jsp").forward(request, response);//轉發到apage.jsp  
  4. <jsp:forward page="d.jsp"/>   //轉發到d.jsp 在JSP中使用  
  5. response.sendRedirect("apage.jsp");//重定向到apage.jsp




推薦網址:

www.adulttool8.com
www.zjsqdqc.com
www.zxdyxzw.com
www.xiaoshidaiys.com
www.dyfcsjt.com
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章