Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a Login Validation with JSF (Java Server Faces)

In this article we will discuss how you may write a simple Login Validation using JSF.

Creating a Java Server Faces application is simple and easy to maintain. The component based approach to render rich UI interface is helpful because the UI components are readily available. The components can be customized and custom components can be developed to further enhance the UI features. In this tutorial, a simple Login Application with standardized JSF UI components will be developed. The application uses a single JSP page called the login.jsp that enables the end user to input username and password details. Upon click of the submit button, basic validations are performed. If there are errors encountered during validation, error messages are displayed. If the validation succeeds, then a success message is displayed.

Creating a JSF project in Eclipse:

Click on File >> New >> Dynamic Web Project and the following dialog will appear.

Creating new project

Figure 1: Creating new project

Under the Configuration subsection, select the JavaServer Faces v1.2 Project. Click next. Keep clicking the next buttons until the following screen appears.

Click next

Figure 2: Click next

Under the JSF Implementation add JSTL library by clicking the manage libraries icon

. Manage libraries

Figure 3: Manage libraries

Upon clicking the manage libraries icon, the following dialog should appear.

Manage libraries dialog

Figure 4: Manage libraries dialog

Click the New… button and it will open the following small dialog. Enter the name of the library.

New user library

Figure 5: New user library

Click the OK button.

Now select the JSTL library and Add Jar files to the library by clicking the “Add Jars” or “Add External Jars” button, depending on the location of the jar.

Preferences

Figure 6: Preferences

The following screenshot shows how the dialog looks after adding the jar files:

Adding the jar files

Figure 7: Adding the jar files

Click OK and then make sure the check box against JSTL is checked.

Finishing project

Figure 8: Finishing project

Click finish.

That creates the Java Server Faces project. Now, the following files have to be created.

Listing 1: Login.java

packagecom.src.jsfsample.model;
public class Login {
	private String username;
	private String password;
	privatebooleanisUsernameValid;
	privatebooleanisPasswordValid;
	privatebooleanvalidationComplete = false;
	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}
	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password 
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/**
	 * @return the isUsernameValid
	 */
	publicbooleangetIsUsernameValid() {
		returnisUsernameValid;
	}
	/**
	 * @paramisUsernameValid the isUsernameValid to set
	 */
	public void setUsernameValid(booleanisUsernameValid) {
		this.isUsernameValid = isUsernameValid;
	}
	/**
	 * @return the isPasswordValid
	 */
	publicbooleangetIsPasswordValid() {
		returnisPasswordValid;
	}
	/**
	 * @paramisPasswordValid the isPasswordValid to set
	 */
	public void setPasswordValid(booleanisPasswordValid) {
		this.isPasswordValid = isPasswordValid;
	}
	/**
	 * @return the validationComplete
	 */
	publicbooleangetValidationComplete() {
		returnvalidationComplete;
	}
	/**
	 * @paramvalidationComplete the validationComplete to set
	 */
	public void setValidationComplete(booleanvalidationComplete) {
		this.validationComplete = validationComplete;
	}

	public String checkValidity() {
		if (this.username == null || this.username.equals("") ){
			isUsernameValid = false;
		}
		else {
			isUsernameValid = true;
		}
		if (this.password == null  || this.password.equals("")) {
			isPasswordValid = false;
		} 
		else {
			isPasswordValid = true;
		}
		validationComplete = true;
		return "success";
	}
}

The Login.java class acts as the Managed Bean for this application. A Managed Bean in JSF is a little similar to the ActionForm in Struts. The major difference is that JSF Managed Bean is not required to extend any super class for the purposes of the framework. This gives lot of flexibility to the java developer as the developer still has control over class hierarchy unlike struts. A Managed Bean class includes properties, their getter/setter methods and event handler methods. In the above example, there are two screen related properties - username and password and three technical properties that include isUsernameValid, isPasswordValid and validationComplete. The three technical properties are not linked to any UI component but are used to control the UI presentation. The checkValidate() method is the only event handler method available in the above Managed Bean.

The below class becomes a Managed Bean only after registering it in the faces-config.xml. Thus, any POJO class can become a managed bean by simply registering it with faces-config.xml

Listing 2: Register the Managed Bean in 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_1_2.xsd"
version="1.2">
	<managed-bean>
		<managed-bean-name>login</managed-bean-name>
		<managed-bean-class>com.src.jsfsample.model.Login</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>

</faces-config>

The managed-bean-name tag registers the alias name for the bean class. This name is used in the jsp pages to access the actual bean.

Managed-bean-class is the fully qualified name of the managed bean class.

Managed-bean-scope signifies the scope in which the bean will be stored. There are four available scopes - none, request, session and application.

Listing 3: login.jsp

<%@ page contentType="text/html"%>
<%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%>
<%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head><title>JSF Login Application</title></head>
<body>
<h:form>
<h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}">
<h:outputText value="Username is a Required Field" rendered="#{!login.isUsernameValid}" style="color:red"></h:outputText>
<br>
<h:outputText value="Password is a Required Field" rendered="#{!login.isPasswordValid}" style="color:red"></h:outputText>
</h:panelGroup>
<h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and login.isPasswordValid)}">
<h:outputText value="Username & Password are valid" style="color:green"></h:outputText>
</h:panelGroup>
<table>
<tr>
<td><h:outputText value="Enter Username: " /></td>
<td><h:inputText id="username" 
value="#{login.username}" />
</td>
</tr>
<tr>
<td><h:outputText value="Enter Password: " /></td>
<td><h:inputSecret id="password" 
value="#{login.password}" />
</td>
</tr>
<tr>
<td></td>
<td><h:commandButton value="Login" 
action="#{login.checkValidity}"/>
</td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>

There are key JSF features in this JSP page. Here is the detailed description of each of the features used.

<%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%>
<%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%>

This line links to the jsf core and jsf html tag libraries. The jsf html tag library carries regular html components like text box, buttons, etc.

<f:view></f:view>

This tag at the beginning of the document acts as a container for all the components enclosed between them.

<h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}">
<h:outputText value="Username is a Required Field" rendered="#{!login.isUsernameValid}" style="color:red"></h:outputText>
<br />
<h:outputText value="Password is a Required Field" rendered="#{!login.isPasswordValid}" style="color:red"></h:outputText>
</h:panelGroup>
<h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and login.isPasswordValid)}">
<h:outputText value="Username & Password are valid" style="color:green"></h:outputText>
</h:panelGroup>

The above code snippet is intended to display error and success messages. The first part displays the error messages one after the other. The second part displays a single success message. This code uses Expression Language (EL) to do conditional checks and reference the managed bean values.

The following line in the above code snippet checks to see if the validation failed before displaying the error messages

<h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}">

The rendered attribute, when set to true, displays the enclosed components. When the rendered attribute is set to false, the enclosed components are hidden in the User Interface. The EL "#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}"checks if validation is complete and if either username or password has validation errors. If the EL evaluates to true, the error message is shown on the screen. If the EL, evaluates to false, the error messages are hidden. Similar logic is used for displaying success message.

Here is a brief description of the components used in the login.jsp file.

  1. h:outputText- renders a label
  2. h:inputText - renders a text box.
  3. h:inputSecret - renders a password box
  4. h:commandButton - renders a button that submits the form to the event handler mentioned in the action attribute.

Once done, run by doing a right click on the login.jsp file. The following error message appears when username and/or password are empty while clicking the button.

Error message

Figure 9: Error message

If there is some input in the username and password, the following success message appears.

Validation done

Figure 10: Validation done

This is all for today. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login