环境:jdk8 mysql8.X
数据库准备
数据库login
数据表logintable
代码目录
input.html 输入用户信息
login.jsp 连接数据库,判断用户名是否正确
successful.jsp 成功登陆界面
error.jsp 失败界面
页面展示
代码
input.html
<!DOCTYPE html>
<html>
<head>
<title>input.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<h3>用户登录界面</h3>
<form action="login.jsp" method="post">
用户名:<input type="text" name="username" placeholder="username" style="width:140px;height:20px;"><br>
密 码:<input type="password" name="password" placeholder="password" style="width:140px;height:20px;"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
login.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
//1 加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
out.println("加载类没有找到");
}
//2 建立数据库连接
String url="jdbc:mysql://localhost:3306/login?serverTimezone=UTC";
Connection con = null;
try {
con=DriverManager.getConnection(url, "root", "123456");
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println("建立数据库连接失败");
}
//3 发送sql语句
String username=request.getParameter("username");
String password=request.getParameter("password");
String sql="SELECT * FROM logintable where username='"+username+"' and password='"+password+"' ";
PreparedStatement ps=null;
try {
ps=con.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs=ps.executeQuery(sql);
if(rs.next()){
out.print("登陆成功");
response.sendRedirect("successful.jsp");
}
else{
response.sendRedirect("error.jsp");
}
%>
</body>
</html>