2.制作jsp登录页面 login.jsp 提交到dologin.jsp,使用jdbc连数据库,判断输入的用户名密码是否存在
3.如果存在,把用户名保存在SESSION中,跳转到welcome.jsp,welcome.jsp中读取session中的用户名,显示欢迎你xxx
4.若不存在,跳到登录页面。
1.index.jsp界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="doLogin.jsp" method="post" >
用户名:<input type="text" name="username"/>
<br>
密码:<input type="password" name="password"/>
<br>
<input type="submit" value="登录">
</form>
</body>
</html>
2.login.jsp界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>接受密码并验证</title>
</head>
<body>
<% //获取用户账户输入名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username);
//获取两个数据库里的密码
String rightUsername ="";
String rightPassword ="";
//连接数据库
//连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");//注册驱动
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/firsttry", "root", "root"); //获取连接对象
PreparedStatement preparedStatement = connection.prepareStatement("select * from jsp where username=?");//执行sql语句对象
preparedStatement.setString(1, "zhangsan");
ResultSet resultSet = preparedStatement.executeQuery(); //执行并查询
System.out.println(resultSet);
while (resultSet.next()) {
rightUsername = resultSet.getString("username");
rightPassword = resultSet.getString("userpassword");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (username.equals(rightUsername) && password.equals(rightPassword)) {
session.setAttribute("username", username);
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("index.jsp");
}
%>
</body>
</html>
3.success.jsp界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String username = (String) session.getAttribute("username");
%>
欢迎您!<%=username%>登录成功
</body>
</html>
