我是jsp新手。我正在尝试在 session 过期时重定向到登录页面。
我的代码:
String sessionUser = null;
sessionUser = session.getAttribute("UserName").toString();
if(sessionUser == "" || sessionUser == null)
{
System.out.println("In login");
response.sendRedirect("login.jsp");
}
else
{
System.out.println("out login");
}
在上面的代码中,我在
行中遇到错误sessionUser = session.getAttribute("UserName").toString();
错误
HTTP Status 500 - An exception occurred processing JSP page
我该怎么做?
最佳答案
根据错误消息和您的描述,您似乎已经在 JSP 中编写了此代码:
sessionUser = session.getAttribute("UserName").toString();
如果 session
为 null
或 session
没有 UserName
属性,上面的行可能会引发错误.在 JSP 中编写 scriptlet 是不好的做法。
您需要使用 Filter做任何更接近你想做的事情:
// Do not create session if it doesn't exist
HttpSession session = request.getSession(false);
// check if session is null
if(session != null) {
chain.doFilter(request, response);
} else {
// redirect to login page
response.sendRedirect("/login.jsp");
}
您可以实现HttpSessionListener监听 session 失效事件。但监听器在这里并不是一个好的选择,因为它不与请求绑定(bind)。
关于java - Jsp session 和重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17064679/