title: When is session created during JSF login?
body: <p>In JSF, it seems that sessions are created <strong>before</strong> a successful login.  i.e. simply requesting the login page causes a new session to be created.</p>
  
  <p>It seems very wasteful (and vulnerable to DDoS attacks) to create a session for each request received, rather than each successfully logged in user. </p>
  
  <p>The code below is pretty generic, but shows the kind of simple scenario I'm referring to.</p>
  
  <p>index.xhtml:</p>
  
  <pre><code>&lt;html&gt;
      &lt;body&gt;
          &lt;h:form id="login"&gt;
              &lt;h:outputLabel for="username"&gt;Username&lt;/h:outputLabel&gt;
              &lt;p:inputText id="username" name="username" value="#{userController.username}"/&gt;
              &lt;h:outputLabel for="password"&gt;Password&lt;/h:outputLabel&gt;
              &lt;p:password id="password" name="password" value="#{userController.password}"/&gt;
  
              &lt;p:commandButton id="loginButton" value="login" action="#{loginController.login}"/&gt;
          &lt;/h:form&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>LoginController.java</p>
  
  <pre><code>@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()));
          }
      }
  
      // username and password getters/setters
  
  }
  </code></pre>
  
  <p><strong>Edit: shambolic code example fixed</strong></p>