javaweb用户登录案例

目录

    • 用户登录案例需求:
    • 分析:
    • 开发步骤:
      • 1.创建项目,导入html页面,配置文件,jar包
      • 2. 创建数据库环境:
      • 3.创建包cn.itcast.domain,创建类User
      • 4.创建包cn.itcast.util,编写工具类JDBCUtils
      • 5.创建包cn.itcast.dao,创建类UserDao,提供login方法;
      • 6.测试类test01
      • 6. 编写cn.itcast.web.servlet.LoginServlet类
      • 7. 编写FailServlet和SuccessServlet类
      • 8. login.html中form表单的action路径的写法
      • 9. 启动项目并运行,检验效果
      • 10. 使用BeanUtils工具类,简化数据封装

简单的用户登录案例,仅实现简单的逻辑

用户登录案例需求:

1.编写login.html登录页面
	username & password 两个输入框
2.使用Druid数据库连接池技术,操作mysql,day14数据库中user表
3.使用JdbcTemplate技术封装JDBC
4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

分析:

开发步骤:

1.创建项目,导入html页面,配置文件,jar包

html页面内容:
login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="" method="post">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name="password"><br>

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

    </form>
</body>
</html>

配置文件druid.properties,注意编码问题,以防出现乱码:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day14?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

导入的jar包:
javaweb用户登录案例_第1张图片

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 java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/*
*  JDBC工具类,使用Druis连接池
*
* */
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.测试类test01

测试数据,查看是否有问题

package cn.itcast.test;

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

public class test01 {
    @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);
    }

}

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 {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //1. 设置编码
        request.setCharacterEncoding("utf-8");
        //2. 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3. 封装请求参数
        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){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            //登陆成功
            //存储数据
            request.setAttribute("user",user);
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }
}

7. 编写FailServlet和SuccessServlet类

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

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

8. login.html中form表单的action路径的写法

  • 虚拟目录+Servlet的资源路径

9. 启动项目并运行,检验效果

10. 使用BeanUtils工具类,简化数据封装

先将commons-beanutils-1.8.0.jar导入项目,

将LoginServlet的代码改进为如下,注意导入的包围 import org.apache.commons.beanutils.BeanUtils;:

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 {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //1. 设置编码
        request.setCharacterEncoding("utf-8");
       /* //2. 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3. 封装请求参数
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);*/
       // 2. 获取所有的请求参数
        Map<String ,String[]> map = request.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){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            //登陆成功
            //存储数据
            request.setAttribute("user",user);
            System.out.println("转发:"+user.toString());
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }
}

这样就能一次把所有的数据获取出来,一次把所有数据封装成一个对象,将来不管是几个参数,都会这么封装好。

BeanUtils工具类知识点补充:
用于简化数据封装,用于封装JavaBean的

  1. JavaBean:标准的Java类
  • 要求,需要遵守的规范:
    1.类必须被public修饰
    2.必须提供空参的构造器
    3.成员变量必须使用private修饰
    4.提供公共setter和getter方法
    之前经常写的实体类就符合这样的规则,是特别简单的javabean
  • 功能:封装数据
  1. 概念:
    成员变量:
    属性:setter和getter方法截取后的产物
    例如:getUsername() --> Username–> username
    属性和成员变量大多数时候都是一样,可以不一样

  2. 方法:
    1.setProperty()
    2.getProperty()
    3.populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中

你可能感兴趣的:(前端,javaweb)