前后端交互:登录案例(详细描述)

今天又是学习的一天呐(敲代码改Bug加摸鱼…)


文章目录

    • 今天又是学习的一天呐(敲代码改Bug加摸鱼...)
    • 前言:
    • 登录案例描述:
    • 项目结构:
    • 项目分析:
    • 数据库:
    • druid.properties
    • 用户实体类:User
    • JDBC工具类:JDBCUtils
    • 操作数据库中User表的类:UserDao
    • 测试类:UserDaoTest
    • 登录的具体逻辑:LoginServlet:
    • 数据封装类测试:BeanUtilsTest:
    • 登录主页:login.html
    • 登录失败跳转:jumpfail.html
    • 登录成功跳转:jumpsuccess.html
    • 启动项目:
    • 最终效果:

前言:

通过这几天在(B站大学)学习的 数据库连接池, Request,Http协议,servlet,等一系列JavaWeb相关知识,今天就写一篇基于前后端交互的登录案例文章,但由于知识有限,边学边做,功能很简陋,用户体验一般般,后期会在更一篇完善的文章的。发这篇文章的目的是巩固巩固这几天的所学知识,同时也分享一下,不足之处欢迎看到的大佬指点!

登录案例描述:


  1. 登录首页:可以输入用户名和密码,有登录按钮,美观,大方!
  2. 使用Druid数据库连接池技术,操作mysql的login1数据库中的user表
  3. 使用JdbcTemplate技术封装JDBC
  4. 用户点击登录按钮,后台程序判断数据库user表里有没有此人,若有此人,在判断用户名、密码是否正确,都正确则登录成功,否则登录失败。
  5. 登录成功,则5s后跳转到我的博客首页
  6. 登录失败,则5s后返回登录首页,可以重新登录

项目结构:

前后端交互:登录案例(详细描述)_第1张图片

前后端交互:登录案例(详细描述)_第2张图片
记得依赖要导入这个项目模块!

项目分析:

前后端交互:登录案例(详细描述)_第3张图片


数据库:

create database login1;
use login1;

create table user(
	id int primary key auto_increment,
	username varchar(32) unique not null,
	password varchar(32) not null
);

insert into user values(1,"AAA","123");
insert into user values(2,"小明","123456");

druid.properties

(password为自己的密码)

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/login1
username=root
password=******
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
maxWait=3000

filters=stat
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200


用户实体类:User

package com.example.LoginCase;

/**
 * 用户的实体类
 */
public class User {

    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 + '\'' +
                '}';
    }
}


JDBC工具类:JDBCUtils

package 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();
    }
}


操作数据库中User表的类:UserDao

package dao;


import com.example.LoginCase.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

/**
 * 操作数据库中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;
        }
    }
}

测试类:UserDaoTest

package test;


import com.example.LoginCase.User;
import dao.UserDao;
import org.testng.annotations.Test;

public class UserDaoTest {

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

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

        System.out.println(user);
    }
}


登录的具体逻辑:LoginServlet:

package web.servlet;
import org.apache.commons.beanutils.BeanUtils;
import com.example.LoginCase.User;
import dao.UserDao;

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){
            //登录失败
            //跳转页面语句
            resp.sendRedirect("/jumpfail.html");
        }else{
            //登录成功
            //跳转页面语句
            resp.sendRedirect("/jumpsuccess.html");
        }

    }

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


数据封装类测试:BeanUtilsTest:

package test;
import com.example.LoginCase.User;
import org.testng.annotations.Test;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
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();
        }





    }
}


登录主页:login.html

DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    html {
      height: 100%;
    }
    body {
      height: 100%;
    }
    .container {
      height: 100%;
      background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
    }
    .login-wrapper {
      background-color: #fff;
      width: 358px;
      height: 588px;
      border-radius: 15px;
      padding: 0 50px;
      position: relative;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .header {
      font-size: 38px;
      font-weight: bold;
      text-align: center;
      line-height: 200px;
    }
    .input-item {
      display: block;
      width: 100%;
      margin-bottom: 20px;
      border: 0;
      padding: 10px;
      border-bottom: 1px solid rgb(128, 125, 125);
      font-size: 15px;
      outline: none;
    }
    .input-item::placeholder {
      text-transform: uppercase;
    }
    .btn {
      text-align: center;
      padding: 10px;
      width: 100%;
      margin-top: 40px;
      background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
      color: #fff;
    }

    a {
      text-decoration-line: none;
      color: #abc1ee;
    }
  style>
head>
<body>
<div class="container">
  <div class="login-wrapper">
    <div class="header">Logindiv>
    <div class="form-wrapper">
      <form action="/loginServlet" method="post">
      <input type="text" name="username" placeholder="username" class="input-item">
      <input type="password" name="password" placeholder="password" class="input-item">
      <input type="submit" class="btn" value="Login">
      form>
    div>

  div>
div>
body>
html>

登录失败跳转:jumpfail.html

DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
  <style>
    p{
      text-align: center;
      font-size: 50px;

    }
    #time{
      color: red;
    }
  style>
head>
<body>
<form action="/tz">
  <p>用户名或密码错误!p>
  <p>

    <span id="time">5span>秒后跳回登录页面...
  p>
form>

<script>
  var obj=document.getElementById("time");
  var count=5;
  function fun(){
    count--;
    if(count<=1){
      location.href = "/login.html";
      /*    clearInterval(id); */
    }
    obj.innerHTML=count+"";
  }
  var id= setInterval(fun,1000);

script>
body>
html>title>
head>
<body>

body>
html>

登录成功跳转:jumpsuccess.html

DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
  <style>
    p{
      text-align: center;
      font-size: 50px;

    }
    #time{
      color: red;
    }
  style>
head>
<body>
<form action="/tz">
    <p>登录成功!p>
  <p>

    <span id="time">5span>秒后跳转到我的博客首页...
  p>
form>

<script>
  var obj=document.getElementById("time");
  var count=5;
  function fun(){
    count--;
    if(count<=1){
      location.href = "https://blog.csdn.net/weixin_47942875?spm=1011.2124.3001.5343";
      /*    clearInterval(id); */
    }
    obj.innerHTML=count+"";
  }
  var id= setInterval(fun,1000);

script>
body>
html>title>
head>
<body>

body>
html>

启动项目:

浏览器输入:localhost:8080/login.html 进入登录页面


最终效果:

(CSDN对视频不太友好,我转成gif图了)


前后端交互:登录案例(详细描述)_第4张图片

你可能感兴趣的:(Java,tomcat,javaweb)