0.环境准备
项目创建:
导入 MySQL 驱动包:
1.创建测试数据
接下来我们在 MySQL 中创建 usersdb 数据库,并创建 user 数据表,表结构如下:
CREATE TABLE `user` (
`name` char(20) NOT NULL DEFAULT '' COMMENT 'name',
`password` char(10) NOT NULL DEFAULT '' COMMENT 'password'
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
插入一些数据:
INSERT INTO `user`
VALUES
( 'admin', 'admin' ),
( ' guest ', ' 123456 ' ),
( ' guest1 ', ' 123 ' );
2.创建登录 jsp 文件
在 web 目录下创建 login.jsp :
pageEncoding="UTF-8" %>
登录用户登录
用户名:
密 码:
type="password" name="password"/>
type="submit" value="登录"/>
3.创建登录 servlet 处理登录请求
登录成功跳转预设 jsp 文件
所使用 JDBC 操作类参考下文
登录失败则跳回 login.jsp
package login;
import database.JdbcOp;
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;
import java.io.PrintWriter;
import java.sql.ResultSet;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 一般都会在doGet()方法中调用doPost()方法,或者在doPost()方法中调用doGet()方法
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置编码格式,可以防止乱码出现
response.setContentType("text/html; charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
// 获取用户提交过来的用户名和密码,是通过表单中input的name属性获取的
String username = request.getParameter("username");
String password = request.getParameter("password");
String isSignUp = request.getParameter("isSignUp");
PrintWriter out = response.getWriter();
System.out.println(username + ": " + password + " isSignUp: " + isSignUp);
// 获取输出流,用户显示信息,也可以用转发或者重定向
PrintWriter pw = response.getWriter();
try {
JdbcOp jdbc = new JdbcOp();
jdbc.open("usersdb");
ResultSet rs = jdbc.executeQuery("select * from users");
while (rs.next()) {
String nm = rs.getString("name");
String pd = rs.getString("password");
System.out.println("username: " + nm + " password: " + pd);
if (nm.equals(username) && pd.equals(password)) {
HttpSession session = request.getSession();
//将数据存储到session中
session.setAttribute("isLogin", "true");
session.setAttribute("username", username);
out.print("");
out.flush();
out.close();
}
}
jdbc.close();
} catch (Exception e) {
e.printStackTrace();
}
pw.write("login fail");
out.print("");
out.flush();
out.close();
}
}
4.运行项目
输入正确的账号密码:
账号密码验证失败: