【发布时间】:2015-04-18 00:49:39
【问题描述】:
我是 JSF 编程的新手,我的登录/会话出现问题,登录后会丢失。
我想实现一个简单的登录,用户可以输入用户名和密码。于是我写了一个LoginController:
@ManagedBean
@SessionScoped
public class LoginController extends AbstractController{
@PostConstruct
public void initialiseSession() {
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
private String username = "null";
private String password;
private boolean loggedIn = false;
@Inject
private EmployeeService employeeService;
public static final String employeeSessionKey = "user";
public LoginController() {
}
public String login() {
//check username and password and if true redirect to "/"
}
我的 login.xhtml 看起来像:
<h:form id="loginForm">
<h:outputLabel style="font-size:24px" value="Bitte melden Sie sich an!"/>
<p:panelGrid columns="2">
<p:outputLabel id="userOutput" for="userInput" value="Benutzername"/>
<p:inputText id="userInput" value="#{loginController.username}"></p:inputText>
<p:outputLabel id="passwordOutput" for="passwordInput" value="Passwort"/>
<p:inputText id="passwordInput" type="password" value="#{loginController.password}"></p:inputText>
<h:outputText value="Logindaten merken?" id="outputRememberLogin">
<p:selectBooleanCheckbox id="loginCheckbox">
</p:selectBooleanCheckbox>
<p:spacer width="10" id="loginFormLittleSpacer"></p:spacer>
</h:outputText>
<p:commandButton id="loginButton" value="Anmelden" action="#{loginController.login()}" ajax="false" >
</p:commandButton>
</p:panelGrid>
</h:form>
所以当我登录时重定向工作。但是当我转到另一个 .xhtml 页面时,会话会丢失。
为了测试这个,我放了
<p:outputLabel value="#{loginController.username}"/>
在我的页面上。登录后,用户名变为“null”。
这个问题我快疯了。
有什么想法吗?
之前谢谢。
【问题讨论】:
-
在 JSF 托管 bean 中使用 CDI 工件
@Inject是一种不可靠的方式。 -
为什么需要
@PostConstruct注解的方法中的这一行FacesContext.getCurrentInstance().getExternalContext().getSession(true);? (您还应该避免在用户会话中保存密码)。 -
我只是临时保存用户密码以满足测试需要。我添加了行 FacesContext.getCurr... 因为另一个页面上的错误:javax.el.MethodNotFoundException: Method not found: class de.baol.itech.javaee.view.controller.LoginController.initialiseSession()
-
这条消息
javax.el.MethodNotFoundException: Method not found暗示您正在尝试通过EL 访问带有@PostConstruct修饰的方法initialiseSession()。不需要通过 EL 访问带有@PostConstruct注释的方法。避免它也删除这条线FacesContext.getCurrentInstance().getExternalContext().getSession(true);,这也是多余的。选择不同的方式来模拟登录场景。 -
你的
@SessionScoped是从哪个包导入的?
标签: jsf session jsf-2 primefaces login