我有一个登录 servlet,它工作正常。但我希望多个 servlet 能够访问 userID、valid 和 FacultyCB 值以执行不同的功能。我知道最好的方法是使用会话,请提供一个编写示例,并使用我的 Login Servlet 和 ViewRegisteredCoursesServlet 从会话中调用。如果一个对象(bean)存储在:
session.setAttribute("currentSessionUser", user);
如何在 servlet 中从中获取不同的值?前任。用户 ID 和教员CB。
HttpSession session = request.getSession();
session.getAttribute("currentSessionUser");
此外,据我了解,需要转发会话(这不是一个选项,因为单击哪个导航栏会调用 diff servlet)。正确的?
登录Servlet:
LoginBean user = new LoginBean();
try {
String checkBox = request.getParameter("facultyCB");
user.setID(request.getParameter("id"));
user.setPassword(request.getParameter("password"));
if (checkBox != null) {
user.setFacultyCB(true);
} else {
user.setFacultyCB(false);
}
user = LoginDAO.login(user);
if (user.isValid()) {
HttpSession session = request.getSession(true);
if (checkBox != null) {
user.setFacultyCB(true);
} else {
user.setFacultyCB(false);
}
session.setAttribute("currentSessionUser", user);
response.sendRedirect("success_login.jsp"); //logged-in page
} else {
response.sendRedirect("invalid_login.jsp"); //error page
}
查看RegisteredCoursesServlet:
String userID = "100000001";
//Created code to determine term based on course dates
String year = "2012";
String term = "FALL";
try {
List<RegisteredCoursesBean> registeredCoursesArray = ViewRegisteredCoursesDAO.viewRegisteredCourses(userID, year, term);
request.setAttribute("registeredCoursesBean", registeredCoursesArray);
request.getRequestDispatcher("registered_courses.jsp").forward(request, response);
} catch (Throwable theException) {
System.out.println(theException);
}
登录豆:
private String id;
private String password;
private boolean facultyCB;
public boolean valid;
提前非常感谢!