JSF Login Logout Example with Database

JSF Login Logout Example with Database


Posted in : Java Posted on : November 2, 2012 at 1:04 PM Comments : [ 0 ]

In this section we will discuss about login and logout example using database in JSF.

JSF Login Logout Example

In this section we will discuss about login and logout example using database in JSF.

Some applications are developed so as to provide the facility to their registered user. For this the user should be registered on this application i.e. their information should be available to the application i.e. the information should be added to the application's database. Once the user registered with their username and password then they can use that application's facility for which it is developed. And after using the application user would be required to come out from the application. Before, releasing the application user are required to Logout from the application because of avoiding the unauthorized use. So, I have made a simple example in JSF which provides the user to registered the new users by giving a unique username and corresponding password and for the existing user they can login with the given username and password and in last they are facilitate to logout from the application.

Example :

Here I am giving a simple JSF Login Logout example which will demonstrate how can we use the JSF and database together. For this example we will required to create various user interfaces using which an end user can understand what they are required to do. In this example I have created the XHTML pages where I have used the tags of JSF tag libraries to design the user interfaces and validate them with some instructions. I have created home.xhtml page where provided two links one for the existing user and other for the New user for registration. Then created register.xhtml page where the new user can registered by giving the information to the corresponding fields, next created login.xhtml page where the registered user can register by providing the information to the corresponding fields. Then I have created a Java file named User.java where I the code is written for adding the record to the database table and for login and logout the user. Besides these xhtml pages I have created some more xhtml pages which are executed on the return statements written in the java file. These files are not navigated only by the return statement of java program, on the navigation of these files a Navigation rule is defined in the faces-config.xml file. The Navigation Rule is defined on the basis of the return statement. And for the database connection I have created a context.xml file inside the META-INF and in the web.xml file used the <resource-ref></resource-ref> tag.

Table user

CREATE TABLE `user` ( 
`name` varchar(15) NOT NULL, 
`password` varchar(15) DEFAULT NULL, 
PRIMARY KEY (`name`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Directory Structure

Source Code

User.java

package com.devmanuals;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

@ManagedBean(name = "user")
@SessionScoped
public class User {

private String name;
private String password;
private String dbPassword;
private String dbName;
DataSource ds;

boolean isLoginPage = (FacesContext.getCurrentInstance().getViewRoot()
.getViewId().lastIndexOf("login.xhtml") > -1);

public User() {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/database");
} catch (NamingException e) {
e.printStackTrace();
}
}

public String getDbPassword() {
return dbPassword;
}

public String getDbName() {
return dbName;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String add() {
int i = 0;
if (name != null) {
PreparedStatement ps = null;
Connection con = null;
try {
if (ds != null) {
con = ds.getConnection();
if (con != null) {
String sql = "INSERT INTO user(name, password) VALUES(?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
i = ps.executeUpdate();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (i > 0) {
return "success";
} else
return "unsuccess";
}

public void dbData(String uName) {
if (uName != null) {
PreparedStatement ps = null;
Connection con = null;
ResultSet rs = null;

if (ds != null) {
try {
con = ds.getConnection();
if (con != null) {
String sql = "select name,password from user where name = '"
+ uName + "'";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
rs.next();
dbName = rs.getString("name");
dbPassword = rs.getString("password");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
}

public String login() {
dbData(name);
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
if (isLoginPage && (name.equals(dbName) && password.equals(dbPassword))) {
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("username", name);
if (session == null) {
FacesContext
.getCurrentInstance()
.getApplication()
.getNavigationHandler()
.handleNavigation(FacesContext.getCurrentInstance(),
null, "/login.xhtml");
} else {
Object currentUser = session.getAttribute("name");
if (!isLoginPage && (currentUser == null || currentUser == "")) {
FacesContext
.getCurrentInstance()
.getApplication()
.getNavigationHandler()
.handleNavigation(
FacesContext.getCurrentInstance(), null,
"/login.xhtml");
}
}
return "output";
} else {
return "invalid";
}
}

public void logout() {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
FacesContext
.getCurrentInstance()
.getApplication()
.getNavigationHandler()
.handleNavigation(FacesContext.getCurrentInstance(), null,
"/login.xhtml");
}
}

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/database" auth="Container" type="javax.sql.DataSource"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/record"/>

</Context>

home.xhtml

<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<h:head>
<title>Home Page</title>
</h:head>
<h:body>
<h3>Welcome to the Devmanuals</h3>
<table frame="box" border="1">
<tr>
<td width ="75"><center><h:outputLink value="login.xhtml">Sign In</h:outputLink></center></td>
<td width ="75"><center><h:outputLink value="register.xhtml">Sign Up</h:outputLink></center></td>
</tr>
</table>
</h:body>
</html>

register.xhtml

<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<h:head>
<title>Registration Page</title>
</h:head>
<h:body>
<f:view>
<h:form id="registerForm">
<table>
<tr>
<td><h:outputText value="Enter Your Name"/></td>
<td><h:inputText id="name" value="#{user.name}" required="true"
requiredMessage="Name field should be filled"/></td>
<td><h:message for="name" style="color:red"/></td>
</tr>
<tr>
<td><h:outputText value="Enter Password :"/></td>
<td><h:inputSecret id="psw" value="#{user.password}" required="true"
requiredMessage="Password field should be filled"/></td>
<td><h:message for="psw" style="color:red"/></td>
</tr>
<tr>
<td/>
<td><h:commandButton value="Register" action="#{user.add}"/></td>
</tr>
<tr>
<td><h:outputLink value="home.xhtml">Home</h:outputLink></td>
</tr>
</table>
</h:form>
</f:view>
</h:body>
</html>

login.xhtml

<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<h:head>
<title>Login Page</title>
</h:head>
<h:body>
<f:view>
<h:form id="loginForm">
<table frame="box">
<tr>
<th>Login Page</th>
</tr>
<tr>
<td> <h:outputText value="Enter Your Name : "/> </td>
<td> <h:inputText id="inputName" value="#{user.name}" required="true" 
requiredMessage="Name field must not be empty"/> </td>
<td><h:message for="inputName" style="color:red"/></td>
</tr>
<tr>
<td> <h:outputText value="Enter password :"/> </td>
<td> <h:inputSecret id="inputPassword" value="#{user.password}" required="true" 
requiredMessage="Password field must not be empty"/> </td>
<td><h:message for="inputPassword" style="color:red"/></td>
</tr>
<tr>
<td><h:commandButton value="Sign In" action="#{user.login}"/></td>
<td> <h:outputText value="Not a User "/>
<h:outputLink value="register.xhtml">Sign Up</h:outputLink></td>
</tr>
</table>
</h:form>
</f:view>
</h:body>
</html>

success.xhtml

<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<h:head>
<title>Success Page</title>
</h:head>
<h:body>
<f:view>
<p>Successfully logged in</p>
<p>Hi, #{user.name}</p>
<h:form>
<p><h:commandLink value="logout" action="#{user.logout}" /></p>
</h:form>
</f:view>
</h:body>
</html>

error.xhtml

<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<h:head>
<title>Error Page</title>
</h:head>
<h:body>
<f:view>
<p><b>Sorry, either name or password is incorrect please try again</b></p>
<p><h:outputLink value="login.xhtml">Login Again</h:outputLink></p>
</f:view>
</h:body>
</html>

unsuccess.xhtml

<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Unsuccess Page</title>
</h:head>
<h:body>
<f:view>
<p>There is an error in signing up. See Server Console for error.</p>
<h:outputLink value="register.xhtml">Back</h:outputLink>
</f:view>
</h:body>
</html>

Output

When you will execute this example successfully then the output will be as follows :

1. The first output page will be the Home page which will be looked as follows :

2. Now First we will sign up here so, clicked on Sign Up link at the home page then the registration page will be opened as follows :

3. On the registration page I filled the data to the respective fields as Name='deepak' and Password='deepak' and clicked on Register button then the data will be added to the database table ( if no error in adding of data) named 'user' and the success.xhtml page will be invoked and if found any error in registration then the data will be not added to the table and unsuccess.xhtml page will be invoked as follows :

3.1 And the database table will be as follows :

3.2. Now tried to sign up again with the existing name and password then the output will be as follows :

3.3 As per instruction in the unsuccess.xhtml page error will be shown on console server as follows :

4. Now after successfully registration logout from the page and tried to sign in again. The login.xhtml page will be invoked and filled the textboxes values as Name='deepak' and Password='deepak' the sing in page will be looked as follows :

5. After filling the value clicked on Sing In button then the success.xhtml page will be invoked and will looked as follows :

6. Now when you will clicked on logout link then you will be logged out from the page and it will redirect to the login page as follows :

7. And Suppose you are trying to sign in with invalid data (if not available in the database table) i.e. other than the Name='deepak' and Password='deepak' then the error.xhtml page will be invoked and the output will be as follows :

7.1 After clicking on the sign in button output will be as follows :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics