我正在尝试使用jsp设计一个简单的登录系统。在登录页面中,用户输入他的用户名和密码,验证时将其作为
执行if username and password combination exists, then
{
HttpSession session = request.getSession(false);
if (session == null) {
// Session not created yet. So we do it now.
session = request.getSession();
session.setAttribute("id",idvariable );
response.sendRedirect("home.jsp");
// I redirect them to their profile home pages
}
else {
// Session is already created.
response.sendRedirect("home.jsp");
// So i again redirect them to their home page
}
}
现在在“home.jsp”中,如何检查会话是否已经创建?
* 我需要检查配置文件中的每个页面是否已启动会话。所以我想创建一些我可以在每个jsp页面顶部调用的函数*
我该怎么办?
答案 0 :(得分:1)
答案 1 :(得分:1)
首先创建一个这样的类..来设置用户bean属性 这个例子假设一个用户为了简单起见
public class Users implements Serializable {
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
然后登录检查就像这样
String userName = request.getRequest().getParameter("txtid");
String password = request.getRequest().getParameter("txtPassword");
Vector params = new Vector();
params.add(null);//return result from procedure
params.add(Name);
params.add(password);
Users mainUser = new Users ();
Vector tempResults = callingDaoProcedure.executeGetPasswordogin(params);//finds the password in DB
if (!tempResults.isEmpty()) {
mainUser = (MainUsers) tempResults.get(0);
if (mainUser.getPassword().trim().equals(password.trim())) {
HttpSession session = request.getSession(false);
if (request.getSession().getAttribute("userLogin") == null) {
// Session not created yet. So we do it now.
session = request.getSession();
requestgetRequest().setAttribute("status", "NO_ERRORS");
request.getSession().setAttribute("userLogin", mainUser);
response.sendRedirect("home.jsp");
// I redirect them to their profile home pages
}
else {
// Session is already created.
response.sendRedirect("home.jsp");
// So i again redirect them to their home page
}
}
else
{
request.getRequest().setAttribute("status", "WRONG_PASSWORD");
System.out.println("wrong password");
}
}
上面的代码没有错误,但是因为你提供了一个丢失的代码,这与我接触你的情况一样紧密,你可以在每个jsp上访问这个变量,就像这样
<input type="hidden" name="user" id="user" value="${sessionScope['userLogin'].user}">
我希望它有所帮助,最重要的是你从中学到了一些东西
答案 2 :(得分:1)
使用JSP Prelude
将jsp添加到所有jsps的开头。并检查sesion是否已经存在。
参考文献: