用session实现免登录
本帖最后由 她与晚风 于 2023-4-30 12:11 编辑代码如下:
二次免登录页面:
package bj;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.*;
@WebServlet({"/welcome"})
public class welcomePage extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
HttpSession session = request.getSession();
String sql;
String username = null;
String password = null;
if(cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getName();
}
if ("password".equals(cookie.getValue())) {
password = cookie.getValue();
}
}
if(username !=null && password != null){
sql = "select * from t_login where username = ? and password = ?";
System.out.println(username + ": " + password);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees", "root", "123456");
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setInt(2, Integer.parseInt(password));
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
System.out.println("登录成功");
connection.setAutoCommit(true);
session.setAttribute("username",username);
response.sendRedirect(request.getContextPath() + "/dept/List");
//可以执行到这里,到好像跳转的不是List页面,又回到了/index.jsp页面
}else {
System.out.println("登录失败");
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}else {
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
/*
*/
}
}
本帖最后由 她与晚风 于 2023-4-30 12:08 编辑
//Servlet代码主体
package bj;
import MyUtil.DepartmentUser;
import MyUtil.EmoloyeeUser;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
@WebServlet({"/dept/List","/dept/Delete","/dept/Detail","/dept/Update","/dept/login"})
public class ServletList extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees","root","123456");
if("/dept/List".equals(request.getServletPath())){
HttpSession session = request.getSession(false);
///
System.out.println(session);
System.out.println(session.getAttribute("username"));
///
if(session == null || session.getAttribute("username") == null){
//
System.out.println("执行了吗");
//
response.sendRedirect(request.getContextPath() + "/index.jsp");
}else {
connection.setAutoCommit(false);
ArrayList<DepartmentUser> arrayList = new ArrayList<>();
sql = "select department_id,department_name,manager_id,city from departments e left join locations l on e.location_id = l.location_id";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String department_id = resultSet.getString("department_id");
String department_name = resultSet.getString("department_name");
String manager_id = resultSet.getString("manager_id");
String city = resultSet.getString("city");
DepartmentUser departmentUser = new DepartmentUser(department_id,department_name,manager_id,city);
arrayList.add(departmentUser);
}
request.setAttribute("list",arrayList);
connection.setAutoCommit(true);
System.out.println("没毛病");
request.getRequestDispatcher("/deptList.jsp").forward(request,response);
}
} else if ("/dept/Delete".equals(request.getServletPath())) {
HttpSession session = request.getSession(false);
if(session == null || session.getAttribute("username") == null){
response.sendRedirect(request.getContextPath() + "/index.jsp");
}else {
connection.setAutoCommit(false);
String department_id = request.getParameter("department_id");
sql = "delete from departments where department_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, Integer.parseInt(department_id));
int i = preparedStatement.executeUpdate();
sql = "delete from employees where department_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, Integer.parseInt(department_id));
int j = preparedStatement.executeUpdate();
connection.setAutoCommit(true);
if(i !=0 || j != 0){
System.out.println("操作成功");
}
response.sendRedirect(request.getContextPath() + "/dept/List");
}
} else if ("/dept/Detail".equals(request.getServletPath())) {
HttpSession session = request.getSession(false);
if(session == null || session.getAttribute("username") == null){
response.sendRedirect(request.getContextPath() + "/dept/index.jsp");
}else {
connection.setAutoCommit(false);
ArrayList arrayList = new ArrayList();
String department_id = request.getParameter("department_id");
sql = "select employee_id,last_name,job_id,manager_id,department_id,hiredate from employees where department_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, Integer.parseInt(department_id));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String employee_id= resultSet.getString("employee_id");
String last_name = resultSet.getString("last_name");
String job_id = resultSet.getString("job_id");
String manager_id = resultSet.getString("manager_id");
department_id = resultSet.getString("department_id");
String hiredate = resultSet.getString("hiredate");
EmoloyeeUser emoloyeeUser = new EmoloyeeUser(employee_id,last_name,job_id,manager_id,department_id,hiredate);
arrayList.add(emoloyeeUser);
}
connection.setAutoCommit(true);
request.setAttribute("detail",arrayList);
request.getRequestDispatcher("/deptDetail.jsp").forward(request,response);
}
} else if ("/dept/Update".equals(request.getServletPath())) {
HttpSession session = request.getSession(false);
if(session == null || session.getAttribute("username") == null){
response.sendRedirect(request.getContextPath() + "/dept/index.jsp");
}else {
connection.setAutoCommit(false);
String department_id = request.getParameter("department_id");
System.out.println(department_id);
String department_name = request.getParameter("department_name");
String manager_id = request.getParameter("manager_id");
String city = request.getParameter("city");
sql = "update departments set department_name = ?,manager_id = ? where department_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,department_name);
preparedStatement.setInt(2, Integer.parseInt(manager_id));
preparedStatement.setInt(3, Integer.parseInt(department_id));
int j = preparedStatement.executeUpdate();
sql = "update locations set city = ? where location_id = (select location_id from departments where department_id = ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,city);
preparedStatement.setInt(2, Integer.parseInt(department_id));
int i = preparedStatement.executeUpdate();
if(i != 0 && j != 0){
System.out.println("修改成功");
}
connection.setAutoCommit(true);
response.sendRedirect(request.getContextPath() + "/dept/List");
}
} else if ("/dept/login".equals(request.getServletPath())) {
HttpSession session = request.getSession();
String username = request.getParameter("username");
String password = request.getParameter("password");
String flag = request.getParameter("flag");
System.out.println(flag + "lll");
if("1".equals(flag)){
Cookie cookie1 = new Cookie("username",username);
cookie1.setMaxAge(180);
cookie1.setPath(request.getContextPath());
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("password",password);
cookie2.setMaxAge(180);
cookie2.setPath(request.getContextPath());
response.addCookie(cookie2);
}
sql = "select * from t_login where username = ? and password = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setInt(2, Integer.parseInt(password));
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
System.out.println("登录成功");
connection.setAutoCommit(true);
session.setAttribute("username",username);
//aaaaaaaaaaaaaa
System.out.println("-----------------------------------");
response.sendRedirect(request.getContextPath() + "/dept/List");
}else {
System.out.println("登录失败");
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
}finally {
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
我的这个页面登录二次跳转有问题 您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名和密码存储在Cookie中,然后在需要进行身份验证的页面,通过读取Cookie中的信息来实现自动登录。
代码的逻辑如下:
1. 获取请求中的所有Cookie。
2. 遍历这些Cookie,找到名为"username"和"password"的Cookie。
3. 如果找到了这两个Cookie,从这些Cookie中获取用户名和密码。
4. 使用获取到的用户名和密码查询数据库以验证用户身份。
5. 如果用户身份验证成功,将用户名存储在Session中,并将用户重定向到部门列表页面。
6. 如果身份验证失败,将用户重定向到登录页面。
为了让您的代码更清晰,我对您的代码进行了一些重构和注释:
package bj;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.*;
@WebServlet({"/welcome"})
public class welcomePage extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
HttpSession session = request.getSession();
String sql;
String username = null;
String password = null;
// 从Cookie中获取用户名和密码
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
}
if ("password".equals(cookie.getName())) {
password = cookie.getValue();
}
}
}
// 如果找到了用户名和密码,验证用户身份
if (username != null && password != null) {
sql = "select * from t_login where username = ? and password = ?";
System.out.println(username + ": " + password);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees", "root", "123456");
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, username);
preparedStatement.setInt(2, Integer.parseInt(password));
resultSet = preparedStatement.executeQuery();
// 如果身份验证成功,将用户名存储在Session中,并重定向到部门列表页面
if (resultSet.next()) {
System.out.println("登录成功");
connection.setAutoCommit(true);
session.setAttribute("username", username);
response.sendRedirect(request.getContextPath() + "/dept/List");
} else {
// 身份验证失败,重定向到登录页面
System.out.println("登录失败");
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
// 没有找到用户名和密码,重定向到登录页面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
}
这样,您的代码会更易于阅读和理解。 匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...
iskdz 匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...
厉害了哥,可以了,就是欢迎页面有问题
请问一下我写的那个有什么问题呢 匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...
哦哦
username = cookie.getValue();
我这一步写错了{:9_236:}
页:
[1]