In this section we are going to discuss about how a valid user can only be logged in.
JSF User Login Example With Database
In this section we are going to discuss about how a valid user can only be logged in.
Before proceeding I want to explain that what I want to do in this example. In this example I want that only a registered user can logged in. If a user is not registered they will be required to first, register here (Sign Up) and then at the next time they can logged in here directly.
For this I have created a database table named user and then using the Eclipse IDE created a dynamic web project and created the package com.devmanuals inside which created User.java class with some data members and their setter getter methods. This class also contains the methods that facilitate to create a new user and validate the existed user at the time of signing in. For signing up the add() method is called and inserted the data to the table. And the interface that facilitate to signed up the user, I have created register.xhtml page. And the method login() validate the registered user that checks whether, the user trying to signed in is a registered user or not. And for the interface that facilitate to signing in a user, I have created a login.xhtml page. Except these I have created some more xhtml pages which are called on a condition i.e success.xhtml page is called after become signed up and signing up successfully, error.xhtml and unsuccess.xhtml pages are called while a non-registered user is trying to signing in and when an error occurs during registration respectively, home.xhtml page is created because of providing the both options i.e. Sign In and Sign Up to the user. After that I have made some changes to the web.xml file and to the faces-config.xml file (code is being given below). Then created a context.xml file that is used to available database source to the application.
Directory Structure
table user
CREATE TABLE `user` ( `name` varchar(15) NOT NULL, `password` varchar(15) DEFAULT NULL, PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Source Code :
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>
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.RequestScoped; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; @ManagedBean(name="user") @RequestScoped public class User { private String name; private String password; private String dbPassword; private String dbName; DataSource ds; 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(); System.out.println("Data Added Successfully"); } } } 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); if(name.equals(dbName) && password.equals(dbPassword)) { return "output"; } else return "invalid"; } }
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>
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>
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>
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> </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>
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>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <navigation-rule> <description>login user</description> <from-view-id>/login.xhtml</from-view-id> <navigation-case> <from-action>#{user.login}</from-action> <from-outcome>output</from-outcome> <to-view-id>/success.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{user.login}</from-action> <from-outcome>invalid</from-outcome> <to-view-id>/error.xhtml</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <description>register new user</description> <from-view-id>/register.xhtml</from-view-id> <navigation-case> <from-action>#{user.add}</from-action> <from-outcome>success</from-outcome> <to-view-id>/success.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{user.add}</from-action> <from-outcome>unsuccess</from-outcome> <to-view-id>/unsuccess.xhtml</to-view-id> </navigation-case> </navigation-rule> </faces-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jsfJdbcLoginExample</display-name> <welcome-file-list> <welcome-file>/home.xhtml</welcome-file> </welcome-file-list> <resource-ref> <description>Login Database</description> <res-ref-name>jdbc/database</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> <url-pattern>*.jsf</url-pattern> <url-pattern>*.xhtml</url-pattern> <url-pattern>*.jsp</url-pattern> </servlet-mapping> <context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> </web-app>
Output :
At first we will see the database table
When you will execute this example you will see the home page like as :
At the home page you can see there are two links are given for the users. Sign In is for the registered user and Sign Up is for the non-registered user.
Lets assume that the user is not registered so first click on the Sign Up link then the register.xhtml page will be invoked and it will look like as follows :
When you will provide the value to the respective fields and click on the Register button then success.xhtml page will be invoked and the output will be as follows :
And when you will see the database table then you will see that the record is inserted to the table as follows :
Now if you will click on the Sign In link at the home page then login.xhtml page will be invoked and the page will be look like as follows :
Now if you will provide the value to the corresponding fields like Name='Ankit' and Password="ankits" then success.xhtml page will be invoked and the page will be look like as follows :
If you will provide the wrong value and tried to Sign In then the error.xhtml page will be invoked and the page will be look like as follows :
And if you will do any wrong in the registration page like I have tried here to register with the existing name then the unsuccess.xhtml page will be invoked and the page will be look like as follows :
As per instruction given in the unsuccess page if you will see the console it will show you the error belongs why the problem is occurred during registration.
[ 0 ] Comments