Simple Database Application with JSF (User Login)
January 21, 2010 56 Comments
Here I am not going to show you step wise operation but I am only providing you the source code for each file that I have implemented for a Login application based on database. I hope you can easily follow these instructions after going through first three tutorials that I had published in previous post .
Here in this example we are having a login page. On Login button click, the username and password will get checked for login, if succeed then directed to success page otherwise ask to retry. And yes, I have used JDBC connectivity for MYSQL database. and I have used Netbeans IDE for this application.
Here we have files:
Inside Web Pages directory
login.jsp -for login interface
login_fail.jsp -for re-login interface
success.jsp -page after successful login
Inside WEB-INF directory
faces-config.xml – JSF configuration file
Inside beans package
login_bean.java - here we define the connectivity and logic of the program.
Inside messages package
message.property -It holds the message for validation.
Inside CSS directory
style.css -CSS styles for the given JSP pages.
Database -db_jsf
Table - tbl_users
Fields -ID, UName, PWord
login.jsp
<%--
Document : Login
Created on : Jan 18, 2010, 7:58:03 PM
Author : Prashant
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LOGIN</title>
</head>
<link rel="stylesheet" type="text/css" href="CSS/style.css">
<body>
<f:view>
<h:form id="login_frm">
<h2>Login Please:</h2>
<table width="250" border="0" cellspacing="0" cellpadding="2">
<tr>
<td colspan="2">
<h:message for="username" styleClass="errorMsg"/><br>
<h:message for="password" styleClass="errorMsg"/>
</td>
</tr>
<tr>
<td><h:outputText value="Username : "/></td>
<td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
</tr>
<tr>
<td><h:outputText value="Password : "/></td>
<td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
</tr>
</table>
</h:form>
</f:view>
</body>
</html>
success.jsp
<%--
Document : success
Created on : Jan 18, 2010, 9:35:40 PM
Author : Prashant
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<f:view>
<h:form>
<h2>Hello <h:outputText value="#{login_bean.username}"/>, you are successfully login.</h2>
</h:form>
</f:view>
</body>
</html>
login_fail.jsp
<%--
Document : Login
Created on : Jan 18, 2010, 7:58:03 PM
Author : Prashant
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LOGIN</title>
</head>
<link rel="stylesheet" type="text/css" href="CSS/style.css">
<body>
<f:view>
<h:form id="login_frm">
<h2>Login Please:</h2>
<table width="250" border="0" cellspacing="0" cellpadding="2">
<tr>
<td colspan="2">
Incorrect Username or Password!!<br>
<h:message for="username" styleClass="errorMsg"/><br>
<h:message for="password" styleClass="errorMsg"/>
</td>
</tr>
<tr>
<td><h:outputText value="Username : "/></td>
<td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
</tr>
<tr>
<td><h:outputText value="Password : "/></td>
<td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
</tr>
</table>
</h:form>
</f:view>
</body>
</html>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ==================== -->
<faces-config version="2.0"
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">
<managed-bean>
<managed-bean-name>login_bean</managed-bean-name>
<managed-bean-class>beans.login_bean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<description>Loging Page</description>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-action>#{login_bean.checkValidUser}</from-action>
<from-outcome>valid</from-outcome>
<to-view-id>/success.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{login_bean.checkValidUser}</from-action>
<from-outcome>invalid</from-outcome>
<to-view-id>/login_fail.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<description>ReLoging Page</description>
<from-view-id>/login_fail.jsp</from-view-id>
<navigation-case>
<from-action>#{login_bean.checkValidUser}</from-action>
<from-outcome>valid</from-outcome>
<to-view-id>/success.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{login_bean.checkValidUser}</from-action>
<from-outcome>invalid</from-outcome>
<to-view-id>/login_fail.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<application>
<message-bundle>messages.message</message-bundle>
</application>
</faces-config>
login_bean.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author Prashant
*/
import java.sql.*;
import java.util.*;
@ManagedBean(name="login_bean")
@RequestScoped
public class login_bean {
private String username;
private String password;
private String dbusername;
public String getDbpassword() {
return dbpassword;
}
public String getDbusername() {
return dbusername;
}
private String dbpassword;
Connection con;
Statement ps;
ResultSet rs;
String SQL_Str;
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_jsf","root","root");
ps = con.createStatement();
SQL_Str="Select * from tbl_users where UName like ('" + UName +"')";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString(2).toString();
dbpassword=rs.getString(3).toString();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String checkValidUser()
{
dbData(username);
if(username.equalsIgnoreCase(dbusername))
{
if(password.equals(dbpassword))
return "valid";
else
{
return "invalid";
}
}
else
{
return "invalid";
}
}
}
message.property
# To change this template, choose Tools | Templates # and open the template in the editor. javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.
style.css
/*
Document : style
Created on : Jan 18, 2010, 8:29:32 PM
Author : Prashant
Description:
Purpose of the stylesheet follows.
*/
/*
TODO customize this sample style
Syntax recommendation http://www.w3.org/TR/REC-CSS2/
*/
root {
display: block;
}
body
{
font-family: sans-serif;
font-size: 10px;
color: #000000;
}
h2
{
font-size: 16px;
color: #3d2dff;
font-family:serif;
}
.errorMsg
{
font-size: 12px;
font-family: serif;
font-weight: bold;
color: #FF0000;
padding: 5px;
}
.input_text{
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
border:1px solid #FF7C08;
}
Snaps:
If you have any comment or suggestion on this post, please do comment me.
ref: http://www.roseindia.net/jsf/JSFLoginApplication.shtml
[/sourcecode][/sourcode]





Hi Prachant,
This is a good example of how to connect to mysql using managed beans and JSF.
Now It would be better to show us, for this same example how to use JSF + Spring and hibernate with detailing also the directory hierarchy (where to put the xml, java and jsp files).
Thank you,
Lyes.
Hello Lyes, you are very much welcome… and sorry to say you that, I am just learning JSF. I post what i had practiced. So no much idea about Spring and hibernate. Thank you for your comment..
Tthank you Prachant.
hi can u explain me how to create a login form for multiple users…………
if you can communicate from database, i think you can easily make multiplier login.
Hello lurdhu
Your login form will be for multiple users if it is connected to databases.
First register multiple users with registration form and provide them username and password and store all information into your database and during login check username and password with database.
It will work for multiple users.
If i didn’t understand your question,then plz let me know and explain your question in detail.
may be add the textbox in runtime
like when u click + sign add text boxes
for new user
thank u i got it.but now new problem is that ,when i try to insert values to database via form using jsf..it showing me null pointer exception ….
can u tel me the possible solution for it plz…
thanks in advance
hello lurdhu,
can u tell me the exact location , where the error is coming and paste the error code.
Hi i followed your example but i used a connection to a sql db, after i enter the login and password i get this error
“javax.el.MethodNotFoundException: Method not found: beans.login_bean@5b6b1943.checkValidUser()”
Can you help me?
Thanks
It seems you have not defined checkValidUser() in login_bean class
or you may be using older version of J2EE, please try with J2EE 5 or 6.
I like the example, it helped a lot!
uhmm, how could i do this if the log-in part is a dialog in jquery? if i use actionerrors, the page would redirect somewhere…
Better you create a relogin page, so that if the dialog get error, it will redirect to the relogin page.
Previously, even twitter had same concept.
using this concept into struts may be quite tough(even i may need to check).
but you can use pure struts to achieve like this. Example you can find here
hi!
i want to change this method !
38 public void dbData(String UName)
39 {
40 try
41 {
42 Class.forName(“com.mysql.jdbc.Driver”);
43 con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/db_jsf”,”root”,”root”);
44 ps = con.createStatement();
45 SQL_Str=”Select * from tbl_users where UName like (‘” + UName +”‘)”;
46 rs=ps.executeQuery(SQL_Str);
47 rs.next();
48 dbusername=rs.getString(2).toString();
49 dbpassword=rs.getString(3).toString();
50 }
51 catch(Exception ex)
52 {
53 ex.printStackTrace();
54 System.out.println(“Exception Occur :” + ex);
55 }
56 }
———————————
how to can use Managed Bean to conect database and check validate user and pass ? can you help me!
example:
@ManagedBean(name = “membersController”)
@RequestScoped
public class MembersController implements Serializable {
private Members current;
@EJB
private bean.session.MembersFacade ejbFacade;
public boolean checkValidMember(){
?????….
}
This is too much usefull
Pingback: Java Blogs « Prayag Upd
Hello!
I have a problem. Do you help me, please?
trace:
HTTP Status 500 -
exception
javax.servlet.ServletException: java.lang.NullPointerException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:325)
root cause
javax.faces.el.EvaluationException: java.lang.NullPointerException
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
root cause
java.lang.NullPointerException
beans.login_bean.checkValidUser(login_bean.java:69)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.apache.el.parser.AstValue.invoke(AstValue.java:262)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
org.apache.jasper.el.JspMethodExpression.invoke(JspMethodExpression.java:70)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
Hello Jah, please once check with all the notation that you have used.
I am facening same problem is there any special lib required from notation?
I?ve learn several excellent stuff here. Definitely price bookmarking for revisiting. I wonder how a lot effort you set to make this kind of wonderful informative site.
I have been surfing on-line more than three hours nowadays, yet I by no means discovered any interesting article like yours. It?s pretty price sufficient for me. Personally, if all site owners and bloggers made excellent content material as you did, the internet can be much more helpful than ever before.
Hello there, I discovered your web site via Google whilst searching for a similar topic, your website got here up, it looks good. I’ve bookmarked it in my google bookmarks.
I check this code with jsf 1.2.it runs sucesfully but does not display any message.it stucks on login.jsp page only rather than go toward login_fail.jsp page or success.jsp page.Please assist me soon
Hi Bheem,
Once please check your “faces-config.xml”.
please assist me where to keep CSS file and how to edit message .property manually.
And session by it aplicattion
Generally I do not learn post on blogs, however I would like to say that this write-up very pressured me to take a look at and do so! Your writing style has been surprised me. Thank you, quite nice post.
can u please provide the xml file for this
Sorry Bhavin,
These files are not with me anymore.
javax.faces.PROJECT_STAGE
Development
Faces Servlet
javax.faces.webapp.FacesServlet
1
Faces Servlet
/web/*
30
/web/login.jsp
Constraint1
can u tell me why my login page is not being displayed??
I found this post to be extremely helpful also and for that I thank you. One issue I have is at login success. On your success.jsp page:
Hello , you are successfully login.
My page is a little different in that I require the login (email address) on the login.jsp page, and on success, I want to display the user’s actual name from the database. I am retrieving this successfully as shown in my logs, but cannot get it to display on the success page (mine is called homepage.jsp). It just displays Welcome .
My code for the homepage.jsp page:
Welcome .
Note that I am pulling values from another managed bean on this page also which are bound to actions (buttons) on the page. That should not be a problem though. I don’t know why the “username” property does not show up on the page when rendered. Any ideas with this?
Hi Prashanth,
Wats the url. im not able to see the login page on server publishing. Kindly assist me. Thanks.
thanks prashant for giving this example,but i have some doubt in line no.26 in login.jsp,plz explain.
sorry ,it was line no.27 in login.jsp
Hello anju,
It is just to display the error msg for the given field(password) with some css style.
Thanks for this post. I finally got a managed bean in Netbeans to connect to the sakila DB in MySQL. I have been following the Deitel How to Program 9th ed and they only have an example on how to connect to the JavaDB database.
It is an useful post for JSF learner ….Like me ..We expect this kind of Samples to learn more things…thanks yar..
i am gettting following error on submitting the login form
exception
javax.servlet.ServletException: /login.jsp(25,24) ‘#{login_bean.username}’ Target Unreachable, identifier ‘login_bean’ resolved to null
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
root cause
org.apache.jasper.el.JspPropertyNotFoundException: /login.jsp(25,24) ‘#{login_bean.username}’ Target Unreachable, identifier ‘login_bean’ resolved to null
org.apache.jasper.el.JspValueExpression.getType(JspValueExpression.java:61)
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:81)
javax.faces.component.UIInput.getConvertedValue(UIInput.java:934)
javax.faces.component.UIInput.validate(UIInput.java:860)
javax.faces.component.UIInput.executeValidate(UIInput.java:1065)
javax.faces.component.UIInput.processValidators(UIInput.java:666)
javax.faces.component.UIForm.processValidators(UIForm.java:229)
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1030)
javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:662)
com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:100)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
check the import statement,it should be of faces pkg
import javax.faces.bean.ManagedBean;
how session is managed here ???
Hi, I have some problems with message.property.
Project keeps returing “Can’t find bundle for base name messages.message, locale en_US”. What could be wrong?
hi Prashant,
now i’m using jsf 1.2 and ide using netbeans 6.5. i’m trying login this page..i’m getting login failed…wt i have to dou…plz help me..@narendra
hi im doing ty project . now im creating forms in one of the form when i try to insert a values it showing me null pointer exception so can u givee me some examples so that i can understand it more clearly
On Fri, Jan 11, 2013 at 3:40 PM, Prashant’s Blog wrote:
> ** > Narendra Kumar Charugundla commented: “hi Prashant, now i’m using jsf > 1.2 and ide using netbeans 6.5. i’m trying login this page..i’m getting > login failed…wt i have to dou…plz help me..@narendra” >
hello , can u tell me ur error in detail and also paste ur error code here.
thats good…. will you please tell me how to do the same using hibernate and jsf……
if u know Hibernate then its very easy. u need to write a method in bean class . for details refer hibernate tutorials.
why not all web tutorial explain in detail n whole cycle of web application. mostly done in half half like login example? is there any example that show whole cycle of application like from login went into form, from one form link to another form, from another form can save and edit data n link to the other form. i find no such of this tutorial on the web? how can we beginner write a good program?
If some one needs expert view regarding running
a blog afterward i advise him/her to go to see this webpage,
Keep up the nice work.
Thanks for the post for writing “Simple Database Application with JSF (User
Login) | Prashant’s Blog”. I reallywill really be back again for a great deal more reading through and commenting soon enough. Thank you, Lynell
Can you please help me to connect to the TOAD Database. I am implementing a project in JSF 2.0+JDBC. I need to retrieve set of values from database after entering an input field value in my xhtml page.
hai how to print the page using jsf pls send the jsf code for to print the page pls send the code in my email id
hai how to print the page using jsf pls send the jsf code for to print the page pls send the code in my email id my email id is sindhupriyamca4948@gmail.com
Great blog! Is your theme custom made or did you
download it from somewhere? A design like yours with a few simple tweeks would really make my blog stand out.
Please let me know where you got your theme.
With thanks