jsp 实栗 jsp + jdbc 登录

jsp 实栗 jsp + jdbc 实现登录

实现思路

一个表单页,输入用户登录和密码,然后信息提交到jsp页面进行验证,如果可以服务器跳转到登录成功页,失败,跳转到错误页

跳转的时候窗口的URL地址会发生变化

代码如下

编写登录代码

 登录

<!DOCTYPE html><html lang="zh_CN"><head> <meta charset="UTF-8"> <title>登录</title></head><body> <h1>登录操作</h1> <form action="login_check.jsp" method="post"> <h1>用户登录</h1> <p> 登录id <input type="text" name="id"/> </p> <p> 登录密码 <input type="password" name="password"/> </p> <input type="submit" value="登录"/> <input type="reset" value="重置"/> </form></body></html>

登录处理

<%@ page import="java.sql.*" %><%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午5:50 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Title</title></head><body><%! // 数据库驱动程序 public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver"; // 数据库连接地址 public static final String DBURL = "jdbc:mysql://47.94.95.84:32786/test"; // 用户名 public static final String DBUSER = "root"; // 密码 public static final String DBPASS = "ABCcba20170607";%><% // 连接对象 Connection connection = null; // 操作 PreparedStatement preparedStatement = null; // 结果 ResultSet resultSet = null; // 标志位 boolean falge = false; // 用户真实姓名 String name = null;%><% try{ Class.forName(DBDRIVER); // 获得连接 connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 编写sql验证ID 密码 String sql = "SELECT name FROM user WHERE userid = ? AND password = ?"; // 实例化操作对象 preparedStatement = connection.prepareStatement(sql); // 设置查询内容 preparedStatement.setString(1, request.getParameter("id")); preparedStatement.setString(2, request.getParameter("password")); // 执行查询 resultSet = preparedStatement.executeQuery(); // 如果可以查询到,表示合法用户 if(resultSet.next()){ name = resultSet.getString(1); // 修改标志位 falge = true; } }catch (Exception e){ e.printStackTrace(); }finally { try{ resultSet.close(); preparedStatement.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } }%><% // 登录成功 if(falge){ // 进行服务器端跳转%> <jsp:forward page="./login_sucess.jsp"> <jsp:param name="uname" value="<%=name%>"/> </jsp:forward><% }else{%> <jsp:forward page="./login_failure.html"/><% }%></body></html>

登录完成

<%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午10:22 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Title</title></head><body><h1>登录成功</h1><%=request.getParameter("uname")%></body></html>

登录失败

<%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午10:22 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Title</title></head><body><h1>登录成功</h1><%=request.getParameter("uname")%></body></html>

效果演示

登录界面

相关文章