使用JSP表单记录:
@ManagedBean
@SessionScoped
public class LoginView {
private String username; //+getter +setter
private String password; //+getter +setter
public String submit()
{
try {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance()
.getExternalContext()
.getRequest();
request.login(username, password);
} catch (ServletException e) {
FacesContext.getCurrentInstance().addMessage("login-form:username",
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error", "Incorrect login or password"));
return "/login";
}
return "/index?faces-redirect=true";
}
}
如何检查用户登录的thorug EJB?
以下示例我需要:
@Stateless
public class SessionServiceBean {
@Resource
SessionContext sessionContext;
@EJB
UserService userService;
@Produces
@Named
@LoggedIn
public User getLoggedUser() {
if (/* check user is logged */) {
return userService.getByName(sessionContext.getCallerPrincipal().getName());
}
}
}
我只是认为未记录的使用名称"匿名",但我认为这不是更好的方法。
答案 0 :(得分:0)
您可以将用户的会话信息直接存储在会话范围的bean中。不需要使用HttpServletRequest。例如:
@Named
@SessionScoped
public class UserSession implements Serializable {
private User activeUser;
public void logIn(User user) {
this.activeUser = user;
}
public void logOut() {
activeUser = null;
}
public boolean isLoggedIn() {
return activeUser != null;
}
public User getActiveUser() {
return activeUser;
}
}