登陆页面 login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check.jsp" method="post">
账号:<input type="text" name="username" /><br />
密码:<input type="password" name="password"/><br />
<input type="submit" value="登录"/>
</form>
</body>
</html>
验证页面 check.jsp
如果账号密码错误就会直接重定向到登陆页面重新登陆
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
String URL = "jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8";
String USERNAME="root";
String PASSWORD="admin";
%>
<%
//目的:在数据库中查看是否存在此用户
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
//获取到从登陆页面传过来的账号和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
try{
//a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.jdbc.Driver");
//b.与数据库建立连接
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//c.发送sql语句,执行sql语句
//statement = connection.createStatement();
PreparedStatement ps = connection.prepareStatement("select * from category_ where id=? and name=?");
ps.setString(1, username);
ps.setString(2, password);
resultSet = ps.executeQuery();
if(resultSet.next()){
out.println("登陆成功");
}else{
response.sendRedirect("login.jsp");
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(resultSet != null) resultSet.close();
if(statement != null) statement.close();
if(connection != null) connection.close();
}catch(SQLException e){
e.printStackTrace();
}
}
%>
</body>
</html>