我正在使用有状态 EJB 来保存我的登录信息:
@Stateful
public class SecurityService {
private static final Logger log4jLogger = Logger.getLogger(SecurityService.class);
@Inject UtenteDao utenteDao;
@Inject AutorizzazioneDao autorizzazioneDao;
private Utente utenteCorrente;
private Negozio negozioCorrente;
public SecurityService() {
}
public boolean authenticate() {
boolean result = false;
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal!=null) {
utenteCorrente = utenteDao.findByUsername(principal.getName());
}
if (negozioCorrente!=null && utenteCorrente!=null) {
Autorizzazione a = autorizzazioneDao.cercaPerNegozioAndUtente(negozioCorrente, utenteCorrente);
result = a!=null;
}
return result;
}
// ... }
我的 JSF 登录页面由以下控制:
@Named
@RequestScoped
public class LoginController {
@Inject private SecurityService securityService;
private String username;
private String password;
private Negozio negozio;
public void login() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
if (request.getUserPrincipal() != null) {
request.logout();
}
request.login(username, password);
securityService.setNegozioCorrente(negozio);
if (!securityService.authenticate()) {
throw new ServletException("Utente non abilitato.");
}
externalContext.redirect("/pippo/");
} catch (ServletException e) {
e.printStackTrace();
context.addMessage(null, new FacesMessage("Accesso Negato"));
}
}
public void logout() throws IOException {
//...
}
public String getLoggedUsername() {
Utente utenteCorrente = securityService.getUtenteCorrente();
String fullName = "";
if (utenteCorrente!=null) {
fullName = utenteCorrente.getNomeCompleto();
} else {
System.out.println("Utente NULLO");
}
return fullName;
}
//...
}
我的用户实际上可以按照我想要的方式登录(通过我的域添加一些程序的安全性)。
我遇到的问题是在下一页,当您已经登录时。我想在所有页面标题中显示“欢迎!您以#{loginController.loggedUsername}
.
我不断得到一个null securityService.getUtenteCorrente()
。
SecurityService EJB 的行为类似于无状态会话 bean!我想知道我是否误解了关于有状态 EJB 的某些内容,或者我只是省略了一些内容以使其按预期工作。
我的目标只是拥有一个“会话范围”的 bean 来保持用户状态。是否需要 EJB 或者我可以只使用 SessionScoped JSF ManagedBean?