案例需求:
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码。

  如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误

  如果验证码输入有误,跳转登录页面,提示:验证码错误

  如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您

目录结构

├─src
│ │ druid.properties
│ │
│ └─cn
│   └─imqinhao
│    ├─dao
│    │ UserDao.java
│    │
│    ├─domain
│    │ User.java
│    │
│    ├─servlet
│    │ CheckCodeServlet.java
│    │ LoginServlet.java
│    │
│    └─utils
│    JDBCUtil.java

└─web
│  login.jsp
│  success.jsp

└─WEB-INF
  └─lib
    commons-beanutils-1.8.0.jar
    commons-logging-1.2.jar
    druid-1.2.6.jar
    mchange-commons-java-0.2.12.jar
    mysql-connector-java-8.0.25.jar
    servlet-api.jar
    spring-beans-5.0.0.RELEASE.jar
    spring-core-5.0.0.RELEASE.jar
    spring-jdbc-5.0.0.RELEASE.jar
    spring-tx-5.0.0.RELEASE.jar

创建数据库

先创建数据库

1
CREATE DATABASE day16;

使用day16数据库

1
USE day16;

创建user表

1
2
3
4
5
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(16) NOT NULL
);

写入一些数据

1
2
INSERT INTO USER VALUES(NULL, "qinhao", "qinhao123");
INSERT INTO USER VALUES(NULL, "lareina", "lareina123");

login.jsp

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
51
52
53
54
55
56
57
58
59
60
61
62
<%--
User: qinhao
Date: 2021/7/21
Time: 12:52
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
<script>
window.onload = function () {
document.getElementById("checkCode").onclick = function () {
this.src = "/day16/checkCodeServlet?time=" + new Date().getTime();
}
}
</script>
<style>
div {
color: red;
}
</style>
</head>
<body>
<form action="/day16/loginServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>验证码</td>
<td>
<input type="text" name="checkCode">
</td>
</tr>
<tr>
<td colspan="2">
<img id="checkCode" src="/day16/checkCodeServlet">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录">
</td>
</tr>
</table>
</form>

<div>
<%= request.getSession().getAttribute("checkCode_error") == null ? "" : request.getSession().getAttribute("checkCode_error") %>
<%= request.getSession().getAttribute("common_error") == null ? "" : request.getSession().getAttribute("common_error") %>
</div>
</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
package cn.imqinhao.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 + '\'' +
'}';
}
}

JDBCUtils类

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
package cn.imqinhao.utils;

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;

public class JDBCUtil {
private static DataSource dataSource;

static {
try {
// 加载配置文件
Properties properties = new Properties();
InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
// 初始化连接对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public static DataSource getDataSource() {
return dataSource;
}

public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}

UserDao类

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
package cn.imqinhao.dao;

import cn.imqinhao.domain.User;
import cn.imqinhao.utils.JDBCUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource());

public User login(User loginUser) {
try {
// 编写sql
String sql = "select * from user where username = ? and password = ?";
// 执行sql
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword());
// 返回user对象
return user;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}

}
}

CheckCodeServlet类

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cn.imqinhao.servlet;

import javax.imageio.ImageIO;
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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 100;
int height = 50;
// 1.创建对象,在内存存放图片(验证码图片对象)
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 2.美化图片
Graphics graphics = bufferedImage.getGraphics();
// 填充背景色
graphics.setColor(Color.pink); // 设置画笔颜色
graphics.fillRect(0, 0, width, height); // 填充背景颜色
// 画边框
graphics.setColor(Color.BLUE); // 设置画笔颜色
graphics.drawRect(0, 0, width - 1, height - 1); // 绘制边框

String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
// 生成随机角标
Random random = new Random();
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(str.length()); // 生成随机数索引
// 获取字符
char ch = str.charAt(index); // 抽取随机字符
sb.append(ch);
// 写入验证码
graphics.drawString(ch+"", width / 5 * i, height / 2);
}
String checkCode_str = sb.toString();
// 添加到session中
HttpSession session = req.getSession();
session.setAttribute("checkCode_str", checkCode_str);
// 生成干扰线
graphics.setColor(Color.GREEN);
for (int i = 1; i <= 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}

// 3.将图片输出到页面上
ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
}

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

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
51
52
53
54
55
56
57
58
59
60
61
package cn.imqinhao.servlet;

import cn.imqinhao.dao.UserDao;
import cn.imqinhao.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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取生成的验证码
HttpSession session = req.getSession();
String checkCode = (String) session.getAttribute("checkCode_str");
// 获取用户输入的验证码
String user_checkCode = req.getParameter("checkCode");
// 清除系统生成的验证码
session.removeAttribute("checkCode_str");
if(checkCode != null && checkCode.equalsIgnoreCase(user_checkCode)) {
// 获取输入的数据
String username = req.getParameter("username");
String password = req.getParameter("password");
// 创建user对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 创建userDao对象
UserDao userDao = new UserDao();
User loginUser = userDao.login(user);
// 查到了
if(loginUser != null) {
// 登录成功
// 持久化存储
session.setAttribute("user", user.getUsername());
// 转发
resp.sendRedirect(req.getContextPath() + "/success.jsp");
} else {
// 用户名或密码错误
session.setAttribute("common_error", "账号或密码错误");
// 转发
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
} else {
// 验证码错误
session.setAttribute("checkCode_error", "验证码错误");
// 转发
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}

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

success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%--
Created by IntelliJ IDEA.
User: qinhao
Date: 2021/7/21
Time: 13:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h1><%= request.getSession().getAttribute("user") %>,欢迎您</h1>
</body>
</html>

druid.properties配置文件

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

评论



2019-2021 覃浩的博客 鄂ICP备19020398号-4 正在载入...

PoweredHexo
HostedGitHub & Coding
DNSAliyun & DNSPod
CDNjsDelivr
PictureBedjsDelivr
ThemeVolantis