Request 05 登陸案例

src層

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day14
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000html

cn.itcast.dao

UserDao.java

package cn.itcast.dao;java

import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;mysql

/**web

  • 操做數據庫中User表的類

*/
public class UserDao {spring

//聲明JDBCTemplate對象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

/**
 * 登陸方法
 * @param loginUser 只有用戶名和密碼
 * @return user包含用戶所有數據,沒有查詢到,返回null
 */
public User login(User loginUser){
    try {
        //1.編寫sql
        String sql = "select * from user where username = ? and password = ?";
        //2.調用query方法
        User user = template.queryForObject(sql,
                new BeanPropertyRowMapper<User>(User.class),
                loginUser.getUsername(), loginUser.getPassword());


        return user;
    } catch (DataAccessException e) {
        e.printStackTrace();//記錄日誌
        return null;
    }
}

}sql

cn.itcast.domain

User.java

package cn.itcast.domain;數據庫

/**apache

  • 用戶的實體類

*/
public class User {app

private int id;
private String username;
private String password;

private String gender;

public void setHehe(String gender){
    this.gender = gender;
}

public String getHehe(){
    return gender;
}

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;
}

@Override
public String toString() {
    return "User{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            ", gender='" + gender + '\'' +
            '}';
}

}dom

cn.itcast.test(測試類)

UserDaoTest.java

package cn.itcast.test;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.junit.Test;

public class UserDaoTest {

@Test
public void testLogin(){
    User loginuser = new User();
    loginuser.setUsername("superbaby");
    loginuser.setPassword("123111");


    UserDao dao = new UserDao();
    User user = dao.login(loginuser);

    System.out.println(user);
}

}

BeanUtilsTest.java

package cn.itcast.test;

import cn.itcast.domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;

public class BeanUtilsTest {

@Test
public void test(){

    User user = new User();
    try {
        BeanUtils.setProperty(user,"hehe","male");
        System.out.println(user);

        String gender = BeanUtils.getProperty(user, "hehe");
        System.out.println(gender);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }





}

}

cn.itcast.until(工具類)

JDBCUtil.java

package cn.itcast.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**

  • JDBC工具類 使用Durid鏈接池

*/
public class JDBCUtils {

private static DataSource ds ;

static {

    try {
        //1.加載配置文件
        Properties pro = new Properties();
        //使用ClassLoader加載配置文件,獲取字節輸入流
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);

        //2.初始化鏈接池對象
        ds = DruidDataSourceFactory.createDataSource(pro);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 獲取鏈接池對象
 */
public static DataSource getDataSource(){
    return ds;
}


/**
 * 獲取鏈接Connection對象
 */
public static Connection getConnection() throws SQLException {
    return  ds.getConnection();
}

}

cn.itcast.web(servlet層)

servlet

LoginServlet.java

package cn.itcast.web.servlet;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1.設置編碼 若是數據庫中有中文的話,不設置會致使亂碼
    req.setCharacterEncoding("utf-8");
   /* //2.獲取請求參數
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    //3.封裝user對象
    User loginUser = new User();
    loginUser.setUsername(username);
    loginUser.setPassword(password);*/
    //2.獲取全部請求參數
    Map<String, String[]> map = req.getParameterMap();
    //3.建立User對象
    User loginUser = new User();
    //3.2使用BeanUtils封裝
    try {
        BeanUtils.populate(loginUser,map);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }


    //4.調用UserDao的login方法
    UserDao dao = new UserDao();
    User user = dao.login(loginUser);

    //5.判斷user
    if(user == null){
        //登陸失敗
        req.getRequestDispatcher("/failServlet").forward(req,resp);
    }else{
        //登陸成功
        //存儲數據
        req.setAttribute("user",user);
        //轉發
        req.getRequestDispatcher("/successServlet").forward(req,resp);
    }

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doGet(req,resp);
}

}

clipboard.png

SuccessServlet.java

package cn.itcast.web.servlet;

import cn.itcast.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //獲取request域中共享的user對象
    User user = (User) request.getAttribute("user");

    if(user != null){
        //給頁面寫一句話

        //設置編碼
        response.setContentType("text/html;charset=utf-8");
        //輸出
        response.getWriter().write("登陸成功!"+user.getUsername()+",歡迎您");
    }


}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
}

}

FailServlet.java

package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/failServlet")
public class FailServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //給頁面寫一句話

    //設置編碼
    response.setContentType("text/html;charset=utf-8");
    //輸出
    response.getWriter().write("登陸失敗,用戶名或密碼錯誤");

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
}

}

web層

WEN-INF

lib

clipboard.png

login.html

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Title</title>

</head>
<body>

<form action="/day14_test/loginServlet" method="post">
    用戶名:<input type="text" name="username"> <br>
    密碼:<input type="password" name="password"><br>

    <input type="submit" value="登陸">

</form>

</body>
</html>

案例:用戶登陸

* 用戶登陸案例需求:
    1.編寫login.html登陸頁面
        username & password 兩個輸入框
    2.使用Druid數據庫鏈接池技術,操做mysql,day14數據庫中user表
    3.使用JdbcTemplate技術封裝JDBC
    4.登陸成功跳轉到SuccessServlet展現:登陸成功!用戶名,歡迎您
    5.登陸失敗跳轉到FailServlet展現:登陸失敗,用戶名或密碼錯誤


* 分析

* 開發步驟
    1. 建立項目,導入html頁面,配置文件,jar包
    2. 建立數據庫環境
        CREATE DATABASE day14;
        USE day14;
        CREATE TABLE USER(
        
            id INT PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(32) UNIQUE NOT NULL,
            PASSWORD VARCHAR(32) NOT NULL
        );

    3. 建立包cn.itcast.domain,建立類User
        package cn.itcast.domain;
        /**
         * 用戶的實體類
         */
        public class User {
        
            private int id;
            private String username;
            private String password;
        
        
            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;
            }
        
            @Override
            public String toString() {
                return "User{" +
                        "id=" + id +
                        ", username='" + username + '\'' +
                        ", password='" + password + '\'' +
                        '}';
            }
        }
    4. 建立包cn.itcast.util,編寫工具類JDBCUtils
        package cn.itcast.util;

        import com.alibaba.druid.pool.DruidDataSourceFactory;
        
        import javax.sql.DataSource;
        import javax.xml.crypto.Data;
        import java.io.IOException;
        import java.io.InputStream;
        import java.sql.Connection;
        import java.sql.SQLException;
        import java.util.Properties;
        
        /**
         * JDBC工具類 使用Durid鏈接池
         */
        public class JDBCUtils {
        
            private static DataSource ds ;
        
            static {
        
                try {
                    //1.加載配置文件
                    Properties pro = new Properties();
                    //使用ClassLoader加載配置文件,獲取字節輸入流
                    InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
                    pro.load(is);
        
                    //2.初始化鏈接池對象
                    ds = DruidDataSourceFactory.createDataSource(pro);
        
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        
            /**
             * 獲取鏈接池對象
             */
            public static DataSource getDataSource(){
                return ds;
            }
        
        
            /**
             * 獲取鏈接Connection對象
             */
            public static Connection getConnection() throws SQLException {
                return  ds.getConnection();
            }
        }
    5. 建立包cn.itcast.dao,建立類UserDao,提供login方法
        
        package cn.itcast.dao;

        import cn.itcast.domain.User;
        import cn.itcast.util.JDBCUtils;
        import org.springframework.dao.DataAccessException;
        import org.springframework.jdbc.core.BeanPropertyRowMapper;
        import org.springframework.jdbc.core.JdbcTemplate;
        
        /**
         * 操做數據庫中User表的類
         */
        public class UserDao {
        
            //聲明JDBCTemplate對象共用
            private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        
            /**
             * 登陸方法
             * @param loginUser 只有用戶名和密碼
             * @return user包含用戶所有數據,沒有查詢到,返回null
             */
            public User login(User loginUser){
                try {
                    //1.編寫sql
                    String sql = "select * from user where username = ? and password = ?";
                    //2.調用query方法
                    User user = template.queryForObject(sql,
                            new BeanPropertyRowMapper<User>(User.class),
                            loginUser.getUsername(), loginUser.getPassword());
        
        
                    return user;
                } catch (DataAccessException e) {
                    e.printStackTrace();//記錄日誌
                    return null;
                }
            }
        }
    
    6. 編寫cn.itcast.web.servlet.LoginServlet類
        package cn.itcast.web.servlet;

        import cn.itcast.dao.UserDao;
        import cn.itcast.domain.User;
        
        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;
        
        
        @WebServlet("/loginServlet")
        public class LoginServlet extends HttpServlet {
        
        
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                //1.設置編碼
                req.setCharacterEncoding("utf-8");
                //2.獲取請求參數
                String username = req.getParameter("username");
                String password = req.getParameter("password");
                //3.封裝user對象
                User loginUser = new User();
                loginUser.setUsername(username);
                loginUser.setPassword(password);
        
                //4.調用UserDao的login方法
                UserDao dao = new UserDao();
                User user = dao.login(loginUser);
        
                //5.判斷user
                if(user == null){
                    //登陸失敗
                    req.getRequestDispatcher("/failServlet").forward(req,resp);
                }else{
                    //登陸成功
                    //存儲數據
                    req.setAttribute("user",user);
                    //轉發
                    req.getRequestDispatcher("/successServlet").forward(req,resp);
                }
        
            }
        
            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                this.doGet(req,resp);
            }
        }

    7. 編寫FailServlet和SuccessServlet類
        @WebServlet("/successServlet")
        public class SuccessServlet extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //獲取request域中共享的user對象
                User user = (User) request.getAttribute("user");
        
                if(user != null){
                    //給頁面寫一句話
        
                    //設置編碼
                    response.setContentType("text/html;charset=utf-8");
                    //輸出
                    response.getWriter().write("登陸成功!"+user.getUsername()+",歡迎您");
                }
        
        
            }        


        @WebServlet("/failServlet")
        public class FailServlet extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //給頁面寫一句話
        
                //設置編碼
                response.setContentType("text/html;charset=utf-8");
                //輸出
                response.getWriter().write("登陸失敗,用戶名或密碼錯誤");
        
            }
        
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                this.doPost(request,response);
            }
        }



    8. login.html中form表單的action路徑的寫法
        * 虛擬目錄+Servlet的資源路徑

    9. BeanUtils工具類,簡化數據封裝
        * 用於封裝JavaBean的
        1. JavaBean:標準的Java類
            1. 要求:
                1. 類必須被public修飾
                2. 必須提供空參的構造器
                3. 成員變量必須使用private修飾
                4. 提供公共setter和getter方法
            2. 功能:封裝數據


        2. 概念:
            成員變量:
            屬性:setter和getter方法截取後的產物
                例如:getUsername() --> Username--> username


        3. 方法:
            1. setProperty()
            2. getProperty()
            3. populate(Object obj , Map map):將map集合的鍵值對信息,封裝到對應的JavaBean對象中

其中property操做的是set或者get方法修飾的屬性

clipboard.png
idea打印方法調出參數提示

clipboard.png

相關文章
相關標籤/搜索