我一直试图主要遵循这个答案,但我总是被重定向到我的 login.xhtml (除了当我从登录页面登录时),因为这......
AppManager am = (AppManager) req.getSession().getAttribute("appManager");
始终为空。我一直在尝试在登录屏幕上打印出用户信息,无论我如何到达那里,所有字段(用户名、密码、登录...)始终为空,即使我直接从管理页面输入地址(即登录时获得的位置)。我如何才能保存会话,而不是每次我手动输入地址/离开页面时都被鞭打?
应用管理器:
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import jobapp.controller.Controller;
@ManagedBean(name="appManager")
@SessionScoped
public class AppManager implements Serializable {
private static final long serialVersionUID = 16247164405L;
@EJB
private Controller controller;
private String username;
private String password;
private boolean loggedIn;
private Exception failure;
...
/**
*
* @param e an exception to handle.
*/
private void handleException(Exception e) {
e.printStackTrace(System.err);
failure = e;
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
/**
* The login method.
* calls the controllers login method.
*
*/
public void login(){
try{
failure = null;
loggedIn = controller.login(username, password);
}catch (Exception e){
handleException(e);
}
}
/**
* The logout method.
* Sets the user's info to null
* and stops the conversation.
*/
public void logout(){
username = null;
password = null;
loggedIn = false;
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
...
筛选:
@WebFilter("/faces/admin.xhtml")
public class LoginFilter implements Filter {
...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
//TODO fix "am" nullpointer
AppManager am = (AppManager) req.getSession().getAttribute("appManager");
if (am != null && am.isLoggedIn()) {
// User is logged in, so just continue request.
chain.doFilter(request, response);
} else {
// User is not logged in, so redirect to login.
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/faces/login.xhtml");
}
}