By Pankaj Kumar
Authentication mechanism allows users to have secure access to the application by validating the username and password. We will be using JSF view for login, DAO object ,HttpSession for session management, JSF managed bean and mysql database. Lets now look in detail as how to create a JSF login logout authentication mechanism in JSF application. Step 1: Create the table Users in mysql database as
CREATE TABLE Users(
uid int(20) NOT NULL AUTO_INCREMENT,
uname VARCHAR(60) NOT NULL,
password VARCHAR(60) NOT NULL,
PRIMARY KEY(uid));
Here we create user table with uid as the primary key, username and password fields with not null constraints. Step 2: Insert data into the table Users as;
INSERT INTO Users VALUES(1,'adam','adam');
Before we move on to our project related code, below image shows the project structure in Eclipse. Just create a dynamic web project and convert it to maven to get the project stub and then keep on adding different components. Step 3: Create the JSF login page
login.xhtml
as;
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:h="https://java.sun.com/jsf/html">
<h:head>
<title>login</title>
</h:head>
<h:body>
<h:form>
<h3>JSF Login Logout</h3>
<h:outputText value="Username" />
<h:inputText id="username" value="#{login.user}"></h:inputText>
<h:message for="username"></h:message>
<br></br><br></br>
<h:outputText value="Password" />
<h:inputSecret id="password" value="#{login.pwd}"></h:inputSecret>
<h:message for="password"></h:message>
<br></br><br></br>
<h:commandButton action="#{login.validateUsernamePassword}"
value="Login"></h:commandButton>
</h:form>
</h:body>
</html>
Here we are creating a JSF login view page with username and password fields and set values for these fields through the login managed bean. We invoke the validateUsernamePassword
method on click of Login button to validate the username and password. Step 4: Create the managed bean Login.java
as;
package com.journaldev.jsf.beans;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.journaldev.jsf.dao.LoginDAO;
import com.journaldev.jsf.util.SessionUtils;
@ManagedBean
@SessionScoped
public class Login implements Serializable {
private static final long serialVersionUID = 1094801825228386363L;
private String pwd;
private String msg;
private String user;
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
//validate login
public String validateUsernamePassword() {
boolean valid = LoginDAO.validate(user, pwd);
if (valid) {
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
return "admin";
} else {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd",
"Please enter correct username and Password"));
return "login";
}
}
//logout event, invalidate session
public String logout() {
HttpSession session = SessionUtils.getSession();
session.invalidate();
return "login";
}
}
We declare three String variables user, pwd and msg for username, password and error message fields along with the getter and setter methods. We write a method validateUsernamePassword()
for validating the username and password field by invoking the LoginDAO
class to fetch the username and password from the database and compare it with the front end values passed. If the username and password does not match an error message is displayed as “Incorrect username and password” . Also a logout()
method is written to perform logout by invalidating HTTPSession attached. Step 5: Now create the LoginDAO java class as below. Note that database operations code is not optimized to be used in a real project, I wrote it as quickly as possible because the idea is to learn authentication in JSF applications.
package com.journaldev.jsf.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.journaldev.jsf.util.DataConnect;
public class LoginDAO {
public static boolean validate(String user, String password) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DataConnect.getConnection();
ps = con.prepareStatement("Select uname, password from Users where uname = ? and password = ?");
ps.setString(1, user);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
//result found, means valid inputs
return true;
}
} catch (SQLException ex) {
System.out.println("Login error -->" + ex.getMessage());
return false;
} finally {
DataConnect.close(con);
}
return false;
}
}
In the validate()
method we first establish connection to the database by invoking the DataConnect
class getConnection
method. We use PreparedStatement
to build the query to fetch the data from the database with the user entered values. If we get any data in result set, it means input is valid and we return true, else false. Step 6: Create the DataConnect.java
class as;
package com.journaldev.jsf.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DataConnect {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cardb", "pankaj", "pankaj123");
return con;
} catch (Exception ex) {
System.out.println("Database.getConnection() Error -->"
+ ex.getMessage());
return null;
}
}
public static void close(Connection con) {
try {
con.close();
} catch (Exception ex) {
}
}
}
We load the JDBC driver using Class.forName
method and use DriverManager.getConnection
method passing the url, username and password to connect to the database. Step 7: Create SessionUtils.java to obtain and manage session related user information.
package com.journaldev.jsf.beans;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionUtils {
public static HttpSession getSession() {
return (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
}
public static HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
public static String getUserName() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
return session.getAttribute("username").toString();
}
public static String getUserId() {
HttpSession session = getSession();
if (session != null)
return (String) session.getAttribute("userid");
else
return null;
}
}
Here we obtain a session for each user logged through the getUserId method thereby associating a session id to a particular user id. Step 8: Create the authorization filter class as;
package com.journaldev.jsf.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthorizationFilter implements Filter {
public AuthorizationFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest reqt = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession ses = reqt.getSession(false);
String reqURI = reqt.getRequestURI();
if (reqURI.indexOf("/login.xhtml") >= 0
|| (ses != null && ses.getAttribute("username") != null)
|| reqURI.indexOf("/public/") >= 0
|| reqURI.contains("javax.faces.resource"))
chain.doFilter(request, response);
else
resp.sendRedirect(reqt.getContextPath() + "/faces/login.xhtml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void destroy() {
}
}
We implement the standard filter class by overriding the destroy and doFilter methods. In the doFilter method we will redirect user to login page if he tries to access other page without logging in. Step 9: Create admin.xhtml
as;
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:h="https://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p>Welcome #{login.user}</p>
<h:commandLink action="#{login.logout}" value="Logout"></h:commandLink>
</h:form>
</h:body>
</html>
This page is rendered when the user logs in successfully. Logout functionality is implemented by calling the logout method of the Login.java
class. Step 10: Create faces-config.xml
file as;
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="https://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee
https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>admin</from-outcome>
<to-view-id>/admin.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Once done with all the steps specified above run the application and see the following output in the browser. Login Page Authentication Error Page
Login Success Page
Accessing admin.xhtml while logged in
Just click on the Logout link and the session will be invalidated, after that try to access admin.xhtml page and you will be redirected to the login page, go ahead and download the project from below link and try it out.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Can I use this to show parts of a web site? Content logged users is secure? or render param can be inyectable
- Ivan
Can I use this to show parts of a web site? Content logged users
is secure? or rendered param can be inyectable
- Ivan
nice tutorial, however you forgot to specify mappings on web.xml file i.e. AuthorizationFilter *.AuthirizationFilter AuthorizationFilter /secured/*
- akasozi
Thank’s for this example, I’ve an error in SessionBean, i’m using JSF 2.1, how to import it ?
- Faycal
is it specified which version of JSF is used here ? and what is its jar ?
- Name
Thanks for your tutorial, it was very helpful. is there any way we can use entity class that connect to database? trying not to code the sql statement. Thanks so much
- jacklyn onye
Excellent but I have a question… what happend with AuthorizationFilter
- Boris
Rename the class “SessionBean” in the example immediately. It’s not a bean so the name is confusing.
- Philip Grove
Never ever catch “Exception” in production code, it has loads on unforeseen consequences. I had hoped that it was not done here to promote proper exception handling. Catching “Exception” is sometimes done in the test phase before proper exception handling is done, because proper exception handling on something that might not even work is a waste of time.
- Philip Grove
Upon further investigation of the example it appear to contain code that is never used and code that suggest it has been directly copied from another source. Reveal this source immediately and stop taking credit for the work of others.
- Philip Grove
Hello Pankaj I was reading your tutorial and it really gave me some insights,I tried it myself but it does not work.It does not check username and password against the database but passes the values
- Ainsley
Hi you. Thank you so much. But i have any question. In the file faces-config.xml, why not add a code: controller.SercurityFilter And. I can implements PhaseListener instead of implements Filter in the file AuthorizationFilter. Thank you.
- Thien
very good example. why after logout if you press back button in browser in not invalidated showing the admin page with the name of the logged user? thank you for a reply.
- alfredo fernandes
let’s say in the Users table is a field department , how to map this field to the JSF page?
- Askat
The class name “LoginDAO” is misleading as this it not a DAO object at all, it’s just a simple class which contain one (static) method.
- Krzysiek
Thanks a lot, so helpful what is JSF managed bean behavior with static method? Is it safe with multiple online user? (conflict sessions or not !!)
- Gholamali Irani
Without any entries to web.xml the AuthorizationFilter is never used. Minimum is to include it in web.xml in follwing manner (replace xxxx with your package name): AuthorizationFilter xxxx.filter.AuthorizationFilter This Filter authorizes user access to application. error_page /error/error.xhtml
- Martin Zwernemann
I get an error of java.lang.NullPointerException .How can I fix this ?
- Mustafa Darcan
Dear Pankaj, Thanks a lot. The code you provided helped a lot with my project. One question though, how would you exclude a page from authentication. For example, if you want the user to see the home page first, which should have a link to login page. Any suggestions would be immensely appreciated. Ravi
- ravi
the app seems great though its throwing an exception “java.lang.NullPointerException” why?
- edward
java.lang.NullPointerException -> You have to add the mysql connector library. It was perfect! That’s work fine, thank you.
- Christian
On HttpSession session = SessionBean.getSession(); i’ve error: “error: cannot find symbol” Can you help me?
- Grzesiek
HELO Pankaj. I am using this proekt. How can download package com.journaldev
- Tavakkaljon Dehqonov
I have a problem with this code, everything works great bu if I try to log in multiple users and then log out only one every users session is killed ? Quite a problem or just me ?
- Hrvoje
Hello Pankaj, could you please tell us or better show us with Code how can i check if the Session Timeout is happen and the User hit a button to send a request how can we manage this situation to prevent an Exception because Timeout of the Session ? thanks Raed
- raed
excuse me can you help me to do online nursery system by jsp it’s important to finish it in this weekend… please if you can send to me
- Aisha
this session can be used for multiple users or one, per machine/ip? help please, a feedback would be nice :)
- mhashimi
The warning messages will not render. An error message of “INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.” Any ideas as to why this is occurring?
- Rod Wilson
works great but when i log out i can still go back using the back navigation button .How can i disable it
- ryan
Hi, i took some classes of your code and when I tried to login, it send me that error: Etat HTTP 500 - java.lang.NullPointerException The error pointed to "session.setAttribute (“key”, value), I thought it came from my DBB but after long researchs I just TRY to change the return value in the method HttpSession getSession() and I put. “true” instead of “false” and I don’t know why I could access to the next page after login. I would like to know why :D
- doppioB
Hello, guys i have a problem. I download a project, connect to my DB. But after writing form, i have error. Nullpointer exception.
- Koka
/login.xhtml @13,52 value=“#{login.user}”: Target Unreachable, identifier ‘login’ resolved to null and the import ManagedBean is unused.
- Rafie
why i’ve this error /login.xhtml @12,52 value=“#{login.user}”: Objetivo inalcanzable, identificador [login] resuelto a nulo ?
- Jeff
Hello ! Perfect sample, but i’m connected and i want go to another page but i’m not access Please, can you help me to update methode Best regards.
- JOEL
Some Annotations are deprecated, so change like this: import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.journaldev.jsf.dao.LoginDAO; import com.journaldev.jsf.bean.SessionUtils; import javax.faces.application.FacesMessage; @Named(“login”) @SessionScoped public class Login implements Serializable{
- Marcel Motta
I got almost everything, Just the error message I didn’t get it!
- Marcel Motta
You should really adjust the line around “reqURI.contains(“javax.faces.resource”)”, because many people just to copy & paste. This line would be a large security leach in case users just add “?javax.faces.resource” behind the normal urls.
- Felix Gaebler
Hi, the warning messages will not render. An error message of “INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.” Any ideas as to why this is occurring?
- Christina Back
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.