Servlet案例1:使用者登入,servlet案例

來源:互聯網
上載者:User

Servlet案例1:使用者登入,servlet案例

資料庫準備:

CREATE DATABASE web;USE web;CREATE TABLE users(    id INT PRIMARY KEY AUTO_INCREMENT,    username VARCHAR(64),    PASSWORD VARCHAR(64),    email VARCHAR(64)    );INSERT INTO users (username,PASSWORD,email) VALUES("tom","123","tom@qq.com"),("lucy","123","lucy@qq.com");
View Code

 

對應User類:

package domain;public class User {    private int id;    private String username;    private String password;    private String email;    @Override    public String toString() {        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    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 String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }}
View Code

 

前端頁面:

login.html:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><form action="/WEB2/login" method="post">使用者名稱:<input type="text" name="username"><br/>密碼:<input type="password" name="password"><br/><input type="submit" value="登入" ></form></body></html>
View Code

 

Servlet:

用到c3p0串連池,dbutils工具類,mysql驅動,注意匯入相關包

utils包:

自訂串連池工具類:

package utils;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DataSourceUtils {    private static DataSource dataSource = new ComboPooledDataSource();    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();    // 直接可以擷取一個串連池    public static DataSource getDataSource() {        return dataSource;    }    // 擷取連線物件    public static Connection getConnection() throws SQLException {        Connection con = tl.get();        if (con == null) {            con = dataSource.getConnection();            tl.set(con);        }        return con;    }    // 開啟事務    public static void startTransaction() throws SQLException {        Connection con = getConnection();        if (con != null) {            con.setAutoCommit(false);        }    }    // 交易回復    public static void rollback() throws SQLException {        Connection con = getConnection();        if (con != null) {            con.rollback();        }    }    // 提交並且 關閉資源及從ThreadLocall中釋放    public static void commitAndRelease() throws SQLException {        Connection con = getConnection();        if (con != null) {            con.commit(); // 事務提交            con.close();// 關閉資源            tl.remove();// 從線程綁定中移除        }    }    // 關閉資源方法    public static void closeConnection() throws SQLException {        Connection con = getConnection();        if (con != null) {            con.close();        }    }    public static void closeStatement(Statement st) throws SQLException {        if (st != null) {            st.close();        }    }    public static void closeResultSet(ResultSet rs) throws SQLException {        if (rs != null) {            rs.close();        }    }}
View Code

 

c3p0-config.xml設定檔:

<?xml version="1.0" encoding="UTF-8"?><c3p0-config>    <default-config>        <property name="user">root</property>        <property name="password">xuyiqing</property>        <property name="driverClass">com.mysql.jdbc.Driver</property>        <property name="jdbcUrl">jdbc:mysql:///web</property>    </default-config> </c3p0-config> 
View Code

 

核心類:

package login;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import domain.User;import utils.DataSourceUtils;public class LoginServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //1.擷取使用者名稱密碼        String username = request.getParameter("username");        String password = request.getParameter("password");        //2.資料庫中驗證        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());        String sql = "select * from users where username=? and password=?";        User user = null;        try {            user = runner.query(sql,new BeanHandler<User>(User.class) ,username,password);        } catch (SQLException e) {            e.printStackTrace();        }        if(user!=null){            //登入成功            response.getWriter().write(user.toString());        }else {            //登入失敗            response.getWriter().write("Sorry!Your username or password is wrong.");                    }    }    protected void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}
View Code

 

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?><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">  <display-name>WEB2</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet>    <description></description>    <display-name>LoginServlet</display-name>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>login.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/login</url-pattern>  </servlet-mapping></web-app>
View Code

 

完成!

訪問http://localhost:8080/WEB2/login.html

 

輸入正確的使用者名稱和密碼點擊登入

 

結果如下:

 

完成!

成功!

 

 

接下來,提升功能:

統計成功登入的人數:

package login;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import domain.User;import utils.DataSourceUtils;public class LoginServlet extends HttpServlet {    @Override    public void init() throws ServletException {        int count = 0;        // 域對象        this.getServletContext().setAttribute("count", count);    }    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 1.擷取使用者名稱密碼        String username = request.getParameter("username");        String password = request.getParameter("password");        // 2.資料庫中驗證        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());        String sql = "select * from users where username=? and password=?";        User user = null;        try {            user = runner.query(sql, new BeanHandler<User>(User.class), username, password);        } catch (SQLException e) {            e.printStackTrace();        }        if (user != null) {            // 登入成功            // 利用域對象的方法            ServletContext context = this.getServletContext();            Integer count = (Integer) context.getAttribute("count");            count++;            response.getWriter().write(user.toString() + "You are the " + count + " person to log in successfully");            context.setAttribute("count", count);        } else {            // 登入失敗            response.getWriter().write("Sorry!Your username or password is wrong.");        }    }    protected void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.