使用JSP实现登陆验证

登陆页面 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>
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值