在上一篇章中,我们已经实现了用户注册的案例,那么下面我们接着用户注册的基础,继续来完成 用户登录 案例。
img
image-20191209160307597
image-20210215182650717
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<!-- 提交用户登录的表单请求 -->
<form action="/userDemo/login" method="post">
用户名<input type="text" name="username"><br>
密码<input type="text" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
启动 tomcat 测试访问 login.html 如下:
image-20210215182733967
好了,此时我们已经写好了登录页面,下面我们来处理以下登录的业务Servlet
image-20210215184057652
package com.servlet;
import com.pojo.User;
import com.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
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.sql.SQLException;
/**
* @author Aron.li
* @date 2021/2/15 18:29
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1. 解决乱码
//解决请求参数的中文乱码
request.setCharacterEncoding("UTF-8");
//解决响应中文乱码
response.setContentType("text/html;charset=utf-8");
//2. 获取请求参数username和password
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("登录用户名: " + username + ", 密码:" + password);
//3. 连接数据库校验用户名和密码,也就是执行查询的SQL语句
QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
String sql = "select * from user where username=? and password=?";
//执行查询,查询一条数据,封装到User中
User user = queryRunner.query(sql, new BeanHandler<>(User.class), username, password);
System.out.println("查询到的user数据: " + user);
//4.存在user数据,则登录成功,否之,失败
if (user != null){
// 登录成功,则跳转至 index.html 页面
response.sendRedirect("/userDemo/index.html");
}else {
// 登录失败
response.getWriter().write("登录失败");
}
} catch (Exception e) {
// 登录失败
response.getWriter().write("登录失败");
// 抛出运行时异常
throw new RuntimeException(e.getMessage());
}
}
}
image-20210215184214574
image-20210215184226773
后台数据库查询数据如下:
image-20210215184253967
image-20210215184317350
image-20210215184329315
后台查询的数据如下:
image-20210215184418834