1. 程式人生 > >Servlet學習(三)——實例:用戶登錄並記錄登陸次數

Servlet學習(三)——實例:用戶登錄並記錄登陸次數

插入 and 個數 servlet配置 esc post cep 事務提交 pla

技術分享

1、前提:在Mysql數據庫下建立數據庫web13,在web13下創建一張表user,插入幾條數據如下:

技術分享

2、創建HTML文件,命名為login,作為登錄界面(以post方式提交)

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8     <form action="/WEB13_sevrlet/login"
method="post"> 9 用戶名:<input type="text" name="username"><br/> 10 密碼:<input type="password" name="password"><br/> 11 <input type="submit" value="登錄"><br/> 12 </form> 13 </body> 14 </html>

3、創建連接池

c3p0-config.xml文件如下:

 1 <?
xml version="1.0" encoding="UTF-8"?> 2 <c3p0-config> 3 4 <default-config> 5 <property name="driverClass">com.mysql.jdbc.Driver</property> 6 <property name="jdbcUrl">jdbc:mysql:///web13</property> 7 <property name="user">root</property>
8 <property name="password">12345</property> 9 </default-config> 10 11 </c3p0-config>

DataSourceUtils.java文件如下:(可作為套用模板)

 1 package com.itheima.utils;
 2 
 3 import java.sql.Connection;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 
 8 import javax.sql.DataSource;
 9 
10 import com.mchange.v2.c3p0.ComboPooledDataSource;
11 
12 public class DataSourceUtils {
13     private static DataSource dataSource = new ComboPooledDataSource();
14     private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
15 
16     // 直接可以獲取一個連接池
17     public static DataSource getDataSource() {
18         return dataSource;
19     }
20 
21     // 獲取連接對象
22     public static Connection getConnection() throws SQLException {
23         Connection con = tl.get();
24         if (con == null) {
25             con = dataSource.getConnection();
26             tl.set(con);
27         }
28         return con;
29     }
30 
31     // 開啟事務
32     public static void startTransaction() throws SQLException {
33         Connection con = getConnection();
34         if (con != null) {
35             con.setAutoCommit(false);
36         }
37     }
38 
39     // 事務回滾
40     public static void rollback() throws SQLException {
41         Connection con = getConnection();
42         if (con != null) {
43             con.rollback();
44         }
45     }
46 
47     // 提交並且 關閉資源及從ThreadLocall中釋放
48     public static void commitAndRelease() throws SQLException {
49         Connection con = getConnection();
50         if (con != null) {
51             con.commit(); // 事務提交
52             con.close();// 關閉資源
53             tl.remove();// 從線程綁定中移除
54         }
55     }
56 
57     // 關閉資源方法
58     public static void closeConnection() throws SQLException {
59         Connection con = getConnection();
60         if (con != null) {
61             con.close();
62         }
63     }
64 
65     public static void closeStatement(Statement st) throws SQLException {
66         if (st != null) {
67             st.close();
68         }
69     }
70 
71     public static void closeResultSet(ResultSet rs) throws SQLException {
72         if (rs != null) {
73             rs.close();
74         }
75     }
76 }

4、編寫Servlet實現類

User類代碼如下:

 1 package com.itheima.domain;
 2 
 3 public class User {
 4     private int id;
 5     private String name;
 6     private String password;
 7     
 8     public User(){
 9         
10     }
11     
12     public int getId() {
13         return id;
14     }
15 
16     public void setId(int id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 }

LoginServlet.java代碼如下:

 1 package com.itheima.login;
 2 
 3 import java.io.IOException;
 4 import java.sql.SQLException;
 5 
 6 import javax.servlet.ServletContext;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import org.apache.commons.dbutils.QueryRunner;
13 import org.apache.commons.dbutils.handlers.BeanHandler;
14 
15 import com.itheima.domain.User;
16 import com.itheima.utils.DataSourceUtils;
17 
18 public class LoginServlet extends HttpServlet {
19     
20     @Override
21     public void init() throws ServletException{
22          //在Servletcontext域中存一個數據count
23         int count=0;
24         this.getServletContext().setAttribute("count", count);
25     }
26 
27     public void doGet(HttpServletRequest request, HttpServletResponse response)
28             throws ServletException, IOException {
29         
30         //1.獲得用戶名和密碼
31         String username=request.getParameter("username");
32         String password=request.getParameter("password");
33         
34         //2.從數據庫中驗證該用戶名和密碼是否正確
35         QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
36         String sql="select * from user where username=? and password=?";
37         User user=null;
38         try {
39             user=runner.query(sql, new BeanHandler<User>(User.class),username,password);
40         } catch (SQLException e) {
41             e.printStackTrace();
42         }
43         //3.根據返回的結果給用戶不同顯示信息 
44         if(user!=null){
45             //從Servletcontext中取出count進行++運算
46             ServletContext context=this.getServletContext();
47             Integer count=(Integer)context.getAttribute("count");
48             count++;
49             //用戶登錄成功
50             response.getWriter().write(user.toString()+"--you are success login person"+count);
51             context.setAttribute("count", count);
52         }else{
53             //用戶登錄失敗
54             response.getWriter().write("Sorry,your username or password is wrong!");
55         }
56     }
57 
58     public void doPost(HttpServletRequest request, HttpServletResponse response)
59             throws ServletException, IOException {
60         doGet(request, response);
61     }
62 }

5、編寫Servlet配置文件,代碼如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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_2_5.xsd" id="WebApp_ID" version="2.5">
 3   <display-name>WEB13_sevrlet</display-name>
 4   <context-param>
 5     <param-name>driver</param-name>
 6     <param-value>com.mysql.jdbc.Driver</param-value>
 7   </context-param>
 8   
 9   <welcome-file-list>
10     <welcome-file>index.html</welcome-file>
11     <welcome-file>index.htm</welcome-file>
12     <welcome-file>index.jsp</welcome-file>
13     <welcome-file>default.html</welcome-file>
14     <welcome-file>default.htm</welcome-file>
15     <welcome-file>default.jsp</welcome-file>
16   </welcome-file-list>
17   
18   <servlet>
19     <description></description>
20     <display-name>LoginServlet</display-name>
21     <servlet-name>LoginServlet</servlet-name>
22     <servlet-class>com.itheima.login.LoginServlet</servlet-class>
23   </servlet>
24   <servlet-mapping>
25     <servlet-name>LoginServlet</servlet-name>
26     <url-pattern>/login</url-pattern>
27   </servlet-mapping>
28   
29   <servlet>
30     <description></description>
31     <display-name>ContextServlet</display-name>
32     <servlet-name>ContextServlet</servlet-name>
33     <servlet-class>com.itheima.context.ContextServlet</servlet-class>
34   </servlet>
35   <servlet-mapping>
36     <servlet-name>ContextServlet</servlet-name>
37     <url-pattern>/context</url-pattern>
38   </servlet-mapping>
39 
40 </web-app>

6、測試,訪問“http://localhost:8080/WEB13_sevrlet/login.html”

分別輸入“Tom”,“123”,登錄結果如下:

技術分享技術分享

分別輸入“Lucy”,“1234”,登錄結果如下:

技術分享

分別輸入“Jack”,“123”,登錄結果如下:

技術分享

Servlet學習(三)——實例:用戶登錄並記錄登陸次數