You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
library_manage_system/src/servlet/manager/ManagerLogin.java

62 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package servlet.manager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javabean.Manager;
import net.sf.json.JSONObject;
@WebServlet("/managerLogin") // 定义Servlet的URL映射
public class ManagerLogin extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath()); // 处理GET请求返回简单的响应
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型和字符编码
response.setContentType("application/json; charset=utf8");
PrintWriter out = response.getWriter(); // 获取输出流
// 从请求中获取用户名和密码参数
String user = request.getParameter("user");
String psw = request.getParameter("psw");
// 创建一个HashMap来存储响应数据
HashMap<String, Object> hashMap = new HashMap<String, Object>();
Manager manager = new Manager(); // 创建Manager对象
String result = null; // 用于存储登录结果
try {
result = manager.login(user, psw); // 调用Manager对象的login方法进行登录验证
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace(); // 捕获并打印异常信息
}
if (result.equals("1")) { // 如果登录成功
HttpSession session = request.getSession(); // 获取当前会话
session.setAttribute("manager", user); // 在会话中存储用户名
session.setAttribute("manager_first", "1"); // 标记为首次登录
hashMap.put("code", 0); // 设置响应码为0表示成功
hashMap.put("msg", "登录成功"); // 设置响应消息为登录成功
hashMap.put("url", request.getContextPath() + "/manager/01nav.jsp"); // 设置跳转URL
} else { // 如果登录失败
hashMap.put("code", 1); // 设置响应码为1表示失败
hashMap.put("msg", result); // 设置响应消息为错误信息
}
// 将HashMap转换为JSON对象并写入响应
JSONObject json = JSONObject.fromObject(hashMap);
out.write(json.toString());
}
}