在JSF中,似乎会在成功登录之前创建会话.即,简单地请求登录页面会导致创建新会话.
为每个收到的请求创建会话似乎非常浪费(并且容易受到DDoS攻击),而不是每个成功登录用户.
下面的代码非常通用,但显示了我所指的那种简单场景.
的index.xhtml:
<html>
<body>
<h:form id="login">
<h:outputLabel for="username">Username</h:outputLabel>
<p:inputText id="username" name="username" value="#{userController.username}"/>
<h:outputLabel for="password">Password</h:outputLabel>
<p:password id="password" name="password" value="#{userController.password}"/>
<p:commandButton id="loginButton" value="login" action="#{loginController.login}"/>
</h:form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
LoginController.java
@ViewScoped
public class LoginController implements Serializable {
String username;
String password;
public void login(){
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
if (request.getSession(false) == null){
System.out.println("No session.");
} else {
System.out.println("Session already exists.");
}
try {
request.login(username, password);
} catch (ServletException e) {
FacesContext.getCurrentInstance.addMessage(null, new FacesMessage("Login failure", e.getMessage()));
}
} …Run Code Online (Sandbox Code Playgroud)