请问用户刷新浏览器时如何让家庭会话保持活动状态?
因为登录后,主页会话仍然存在。但是当我刷新浏览器时,它会将我带回登录页面。
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Maxwell
*/
@WebFilter(filterName = "sessionFilter", urlPatterns = {"/*"})
public class sessionFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req1 =(HttpServletRequest)request;
HttpServletResponse res1 =(HttpServletResponse)response;
String session = (String)req1.getSession().getAttribute("pnumber");
String currentPath = req1.getRequestURL().toString();
if(session != null)
{
if(currentPath.contains("login.xhtml"))
{
res1.sendRedirect(req1.getContextPath()+"/home.xhtml");
System.out.println("it is nt empty");
}
else
{
chain.doFilter(request, response);
}
//System.out.println("it is nt empty");
}
else
{
if(currentPath.contains("home"))
{
res1.sendRedirect(req1.getContextPath()+"/login.xhtml");
System.out.println("somefin is wrong");
}
else
{
chain.doFilter(request, response);
}
//System.out.println("somefin is wrong");
}
}
@Override
public void destroy() {
}
}
请问用户刷新浏览器时如何让家庭会话保持活动状态?
因为登录后,主页会话仍然存在。但是当我刷新浏览器时,它会将我带回登录页面。
答案 0 :(得分:1)
刷新页面时控制台中是否有任何警告或错误?那么,对于JSF中的会话管理,我会做以下事情:
1)我使用ManagedBean @SessionScoped,我会在用户登录后将用户信息保存到SessionMap中:
public void login(){
//your code
if(validations){
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().getSessionMap().put("loggedUser", User);
//User is the entity which contains the current user info.
//You can use any data to keep in the SessionMap ;-)
}
}
2)当用户点击注销时,您已使会话无效:
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().invalidateSession();
3)现在,如果您想在用户直接输入网址时验证会话,而无需从登录页面登录:
public void validateSession(){
FacesContext fc = FacesContext.getCurrentInstance();
User currentUser = (User) fc.getExternalContext().getSessionMap().get("loggedUser");
if(currentUser==null){
//shows a message 'Session has caducated'
fc.getExternalContext().redirect("./login.xhtml");
}
}
然后你只需在渲染视图之前调用该方法:
<f:event type="preRenderView" listener="#{loginBean.validateSession()}" />
4)如果您想从任何managedBean获取当前用户数据,您必须从SessionMap获取它:
FacesContext fc = FacesContext.getCurrentInstance();
User user = (User) fc.getExternalContext().getSessionMap().get("loggedUser");
希望这会有所帮助; - )