1.jsp实现登录
思维过程:
1.index.jsp登录界面
2.提交跳转到a.jsp密码匹配检查
3.密码正确就跳转到登陆后界面
Index.jsp代码:
<%--
Created by IntelliJ IDEA.
User: 张川
Date: 2020/4/30
Time: 14:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>form表单交互练习</title>
<style>
.btn-submit{
padding: 0 16px;
font-size: 16px;
color: #fff;
border: none;
border-radius: 4px;
white-space: nowrap;
background-color: #ca0c16;
cursor: pointer;
}
</style>
</head>
<body>
<form method="post" action="a.jsp" class="form-login">
请输入姓名: <input type="text" name="username"><br>
请输入密码: <input type="text" name="password"><br>
<input class="btn-submit" type="submit" value="提交" >
</form>
<%-- action表示接收数据的页面
method表示请求方法 因为是修改数据 一般是post
name是后台request.getParmter("uername")的参数
--%>
</body>
</html>
a.jsp代码:
<%--
Created by IntelliJ IDEA.
User: 张川
Date: 2020/5/9
Time: 21:49
To change this template use File | Settings | File Templates.
--%>
<%@ page import="java.sql.*" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>从index获取数据</title>
</head>
<body>
<%
//获取前端index的登录数据
request.setCharacterEncoding("UTF-8");//编码一定设置
String username=(String)request.getParameter("username");
String password=(String)request.getParameter("password");//取出login.jsp的值
/**
* 查询获得多条数据
* */
//1.将Driver驱动加载进jvm
Class.forName ("com.mysql.jdbc.Driver");
//数据库链接地址 格式 jdbc:mysql:数据库网址/数据库名
String url="jdbc:mysql://localhost:3306/javaweb_learning";
String user="root";
String pwd="123456";
Connection cnn=null;
Statement st = null;
try {
//2.创建链接对象
cnn = (Connection) DriverManager.getConnection (url, user, pwd);
//3。创建sql语句
String sql = "select * from user where name=" + "'" + username + "'";//定义一个查询语句
System.out.println (sql);
//创建链接管道
st = cnn.createStatement ();
//4.执行sql语句
ResultSet res=st.executeQuery(sql);//运行上面的语句
String password2 = null;
while (res.next ()){
password2=res.getString ("password");
}
System.out.println (password2);
if (password.equals (password2)) {
response.sendRedirect ("logined.jsp");
} else {
out.print ("<script language='javaScript'> alert('密码错误');</script>");
response.setHeader ("refresh", "0;url=index.jsp");
}
}catch (Exception e){
}
%>
</body>
</html>
数据库(MySQL)是这样的:
注意:密码正确是跳转页面使用的是:
if (password.equals (password2)) {
response.sendRedirect ("logined.jsp");
}
2.密码正确就返回logined.jsp
登陆后:
密码错误的话: