需求分析

  1. 编写login.html登录页面

    username & password 两个输入框

  2. 使用Druid数据库连接池技术,操作mysql中的user表

  3. 使用JdbcTemplate技术封装JDBC

  4. 登录成功跳转到SuccessServlet

    展示:登录成功!用户名,欢迎您xxx用户

  5. 登录失败跳转到FailServlet

    展示:登录失败,用户名或者密码错误

步骤

  • 导入数据库驱动包,Druid数据库连接池包,JdbcTemplate一系列包

  • 编写登录页面login.html

  • 定义User实体类

  • 定义UserDao数据库连接对象

  • 编写处理登录servlet以及展示页面成功和失败的servlet

代码

项目目录

在这里插入图片描述

登录页面login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<!--用户输入表单-->
<form method="post" action="/demo_login_1/loginServlet" style="margin:auto;">
姓名:<input type="text" name="name" placeholder="输入姓名"></br>
密码:<input type="password" name="password" placeholder="输入密码"></br>
<input type="submit" name="btn" value="提交">
</form>
</body>
</html>

User实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package cn.itcast.domain;

/**
* 实体类,注意这里面的属性要和数据库中的属性写成一样的
* 方便在UserDao中queryForObject使用BeanPropertyMapper
*/
public class User {
private int id;
private String name;
private String password;

public User() {
}

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

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

JDBCUtils.java获取数据库连接池DataSource

druid.properties

1
2
3
4
5
6
7
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day15
username=believe
password=believe
initialSize=5
maxActive=10
maxWait=3000

定义工具类,用于获取DataSource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package cn.itcast.Utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
* JDBC工具类,用于获取数据库连接池
*/
public class JDBCUtils {
private static DataSource ds;
static {

try {
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return ds;
}

}

UserDao数据库连接实体(利用JDBCTemplate)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package cn.itcast.dao;

import cn.itcast.Utils.JDBCUtils;
import cn.itcast.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* 数据库连接获取user信息
* 需要导入的包:1.JDBC驱动:连接数据库
* 2.Druid数据库连接池:创建datasource
* 3.JDBCTemplate:快速创建connection
* 4.BeanUtils:利用反射将map转换为实体对象
*/
public class UserDao {
public static User getUser(User loginUser){

try{
JdbcTemplate jt = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="SELECT * FROM USER WHERE NAME=? AND PASSWORD=?;";
User user = jt.queryForObject(sql,
new BeanPropertyRowMapper<>(User.class),
loginUser.getName(), loginUser.getPassword());//最后两个参数是问号填充
return user;

}catch (Exception e){
e.printStackTrace();
return null;
}

}
}

servlet

LoginServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 {
//获取表单的输入值
request.setCharacterEncoding("utf-8");//设置编码方式
Map<String, String[]> map = request.getParameterMap();
User loginuser = new User();
try {
//将表单输入的map集合转换成一个User对象
BeanUtils.populate(loginuser,map);
User user = UserDao.getUser(loginuser);

if(null==user){
//查询不到就失败,转发到failedServlet
request.getRequestDispatcher("/failedServlet").forward(request,response);

}else{

//查询成功,转发到successServlet
request.setAttribute("user",user);
request.getRequestDispatcher("/successServlet").forward(request,response);

}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

SuccessServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 {
this.doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = (User) request.getAttribute("user");
//设置响应的mime类型,防止乱码
response.setContentType("text/html;charset=utf-8;");
response.getWriter().write("你好,"+user.getName()+"用户!好久不见");
}
}

FailedServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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("/failedServlet")
public class FailedServlet 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 {

//设置响应的mime类型,防止乱码
response.setContentType("text/html;charset=utf-8;");
response.getWriter().write("用户密码错误,登录失败");

}
}

演示

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

项目总结

需要导入哪些jar包?各自有什作用?

  • 数据库驱动jar包

    用于连接数据库,由数据库厂商提供,有统一的接口。

  • Druid数据库连接池jar包

    阿里巴巴提供的数据库连接池技术。通过DruidDataSourceFactory创建

    1
    DruidDataSourceFactory.createDataSource(pro)
  • JDBCTemplate jar包 和 BeanUtils jar包

    JDBC模板,通过JDBCTemplate(DataSource)创建对象。

    再通过对象.queryForObject查询数据库构造实体(比如User)对象。

    需要借助BeanUtils工具类将实体的字节码对象映射到实体对象上去。

    1
    jt.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),sql中的?参数)

JDBCUtils工具类分析

  1. 主要功能

    • 加载读取druid.properties,利用druid数据库连接池工厂创建一个数据库连接池。

      1
      2
      3
      Properties pro = new Properties();
      pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
      ds = DruidDataSourceFactory.createDataSource(pro);
    • 获取数据库连接池

文件目录结构分析

  • dao

    数据库访问对象,实现数据库连接访问操作

  • domain

    定义实体类

  • web

    实现servlet逻辑