I want to store username and password as cookies and allow user to login to a JSF application without entering then on next login.
I have tired OmniFaces to achieve that task. Still the user has to enter the details every-time. The cookies seems not to be stored nor retrieved properly.
How to achieve this functionality in JSF, with or without using OmniFaces?
JSF Controller
package com.beans;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import org.omnifaces.util.Faces;
@Named(value = "webUserController")
@SessionScoped
public class WebUserController implements Serializable {
String username;
String password;
boolean logged = false;
public WebUserController() {
}
@PostConstruct
public void init() {
username = Faces.getRequestCookie("username");
password = Faces.getRequestCookie("password");
logged = canLog();
}
public void loginAction(){
if(canLog()){
logged = true;
Faces.addResponseCookie("username", username, -1);
Faces.addResponseCookie("password", password, -1);
}else{
logged = false;
}
}
public boolean canLog(){
if(username==null||password==null){
return false;
}
if(username.equals("b") && password.equals("b")){
return true;
}else{
return false;
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isLogged() {
return logged;
}
public void setLogged(boolean logged) {
this.logged = logged;
}
}
This is the index.xhtml file.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form >
<h:panelGroup rendered="#{webUserController.logged}" >
<h1>You are logged</h1>
</h:panelGroup>
<h:panelGroup rendered="#{!webUserController.logged}" >
<h1>Please login</h1>
<h:panelGrid columns="2" >
Username
<h:inputText value="#{webUserController.username}" ></h:inputText>
Password
<h:inputText value="#{webUserController.password}" ></h:inputText>
<h:commandButton value="Login" action="#{webUserController.loginAction()}" ></h:commandButton>
</h:panelGrid>
</h:panelGroup>
</h:form>
</h:body>