案例需求:
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
创建数据库
先创建数据库
使用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 { String sql = "select * from user where username = ? and password = ?"; User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword()); 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; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 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(); 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); }
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 = new User(); user.setUsername(username); user.setPassword(password); 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
|