User Login and Registration application
This is the complete explanation of the application in JSF ( Apache MyFaces) with the combined help of Spring and Hibernate frameworks. This is the best example to understand how to make an application using different frameworks. This application starts from user login page. The authenticated user set the user name and password in the appropriate field and is carried to the next page with a message welcoming the user. If the user doesn't set the correct entries then it flashes a message in the same page to indicate that either the user name or password is incorrect. In the user login page, there is a link named "New User" for the new user to get registered with the site i.e. this link carries the new user to the registration page. In this page, the user fills all the required information like user name, password, Email ID and its physical address. In this page, checks have been applied in the fields to verify the correctness of the information. For instance, if the user leaves the required fields blank then appropriate messages for the fields are rendered at the right place, if the new user fills the user name that is already registered with the site then it shows a message "User is already registered", if the user doesn't fill password and confirm password fields same then it makes aware the user sending an appropriate message "The passwords are not same", there is also a check for email id entered by the user. If everything is correct then the user comes to the next page with the message "registration is successful".
Creation of Pages :
This is the first page that appears to the
user. In this page user is asked to fill the user name and password to
login itself in the site. Both the fields are required to fill. If the user
leaves it blank then the message indicating that these can't be left empty is
shown.
Login Page :
login.jsp : The code for above page is given below. For this page CheckValidUser backing bean has been used. On the submission of the page checkUser() method of the bean is called to check the existence of the user in the site. If the user is registered with the site then user is welcomed to the next page otherwise a message that either user name or password is incorrect.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%> <f:view> <html> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <head> <title>User Login</title> <link href="pages/mycss.css" rel="stylesheet" type="text/css"/> </head> <body ><center> <h:panelGrid width="100%" columns="1" border="0" style="padding-left:10px; padding-top:10px; " styleClass="top_bg"> <h:dataTable id="dt1" border="0" cellpadding="0" cellspacing="0" var="ab"> <h:column> <f:facet name="header"> <h:outputText value="RoseIndia" styleClass="style4"/> </f:facet> </h:column> </h:dataTable> </h:panelGrid>
<h:panelGrid width="175px" columns="3" border="0" cellspacing="0"
cellpadding="0">
|
The figure below is shown when user fills user name or password incorrect.
Login Successful Page :
If the user enters correct information then the
user is presented with the next page as in the figure below :
successLogin.jsp : This is the code for above page. This is simple page in which only welcome string is shown to the user.
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%> <f:view> <html> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <head> <title>Welcome</title> <link href="mycss.css" rel="stylesheet" type="text/css"/> </head> <body ><center> <h:form> <h:panelGrid width="100%" columns="1" border="0" style="padding-left:10px; padding-top:10px; " styleClass="top_bg"> <h:dataTable id="dt1" border="0" cellpadding="0" cellspacing="0" var="ab"> <h:column> <f:facet name="header"> <h:outputText value="RoseIndia" styleClass="style4"/> </f:facet> </h:column> </h:dataTable> </h:panelGrid> <h:panelGrid width="100%" columns="1" border="0" > <f:verbatim> </f:verbatim> <h:outputText value=" "/><h:outputText value=" "/><h:outputText value=" "/> </h:panelGrid> <h:outputText value="Welcome ....." style="color:green; font-weight:bold"/> </h:form> </center> </body> </html> </f:view> |
Registration Page :
This page comes to the user if the user is not registered with the site. The
user clicks the link named "New User ?" and so registration page is
opened. The figure below is registration page :
registration.jsp : This is the code for above page. The backing bean used for this page is "Bean". When the page is submitted then register() method is called which checks the user name entered by the user. If the name is already registered then user is informed that the user with name is already registered otherwise a new user object is created and all the fields related with the user is added in that object i.e. user name, password, email, address. Before checking the user existence validateData() method is called to check all the fields. If anything doesn't match with the requirement then the same page is again presented to the user with the validation messages. The messages can be customized creating the MessageFactory class in which messages from the resource bundle for the specific locale are picked and shown in the page. You can see the code for bean below in the tutorial.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%> <f:loadBundle basename="net.roseindia.web.ui.messages" var="message"/> <f:view> <html> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <head> <title>Registration</title> <link href="mycss.css" rel="stylesheet" type="text/css"/> </head> <body ><center> <h:form id="registerForm"> <h:panelGrid width="100%" columns="1" border="0" style="padding-left:10px; padding-top:10px; " styleClass="top_bg"> <h:dataTable id="dt1" border="0" cellpadding="0" cellspacing="0" var="ab"> <h:column> <f:facet name="header"> <h:outputText value="RoseIndia" styleClass="style4"/> </f:facet> </h:column> </h:dataTable> </h:panelGrid> <h:panelGrid width="175px" columns="3" border="0" cellspacing="0" cellpadding="0"> <h:outputText value=" "/> <h:graphicImage id="gi3" value="images/verticle_line.gif" width="4" height="18"></h:graphicImage> <h:panelGroup> <h:dataTable id="dt2" border="0" cellpadding="0" cellspacing="0" width="250" var="gh"> <h:column> <f:facet name="header"> <h:outputText value="User Registration " styleClass="style1"/> </f:facet> </h:column> </h:dataTable> </h:panelGroup> <h:graphicImage id="gi4" value="images/horizontal_line.gif" width="25" height="4" > </h:graphicImage> <h:graphicImage id="gi8" value="images/horizontal_line.gif" width="5" height="4" ></h:graphicImage> <h:graphicImage id="gi6" value="images/horizontal_line.gif" width="260" height="4" ></h:graphicImage> <h:outputText value=" "/> <h:graphicImage id="gi7" value="images/verticle_line.gif" width="5" height="100%" ></h:graphicImage> <h:panelGroup> <h:dataTable id="dt3" border="0" cellpadding="0" cellspacing="0" width="250" var="gh"> <h:column> <f:facet name="header"> <h:outputText value="#{message.already_registered_msg}" style="color:red; font-weight: bold;" rendered="#{Bean.exist}"/> </f:facet> </h:column> </h:dataTable> <h:panelGrid width="100px" columns="2" border="0" cellspacing="2" cellpadding="0"> <h:outputText value="User Name" styleClass="style2"/> <h:panelGroup> <h:inputText id="userName" value="#{Bean.userName}" required="true" size="27" /> <f:verbatim><br/></f:verbatim> <h:message for="userName" styleClass="errors"/> </h:panelGroup> <h:outputText value="Password" styleClass="style2"/> <h:panelGroup> <h:inputSecret id="Password" value="#{Bean.pwd}" size="27" redisplay="true" required="true"/> <f:verbatim><br/></f:verbatim> <h:message for="Password" styleClass="errors" /> </h:panelGroup> <h:outputText value="Confirm Password" styleClass="style2"/> <h:panelGroup> <h:inputSecret id="confirmPassword" value="#{Bean.confPwd}" size="27" redisplay="true" required="true"/> <f:verbatim><br/></f:verbatim> <h:message for="confirmPassword" styleClass="errors" /> </h:panelGroup> <h:outputText value="Email" styleClass="style2"/> <h:panelGroup> <h:inputText id="email" value="#{Bean.email}" size="27" required="true"/> <f:verbatim><br/></f:verbatim> <h:message for="email" styleClass="errors" /> </h:panelGroup> <h:outputText value="Address" styleClass="style2"/> <h:panelGroup> <h:inputText id="address" value="#{Bean.address}" size="27" required="true"/> <f:verbatim><br/></f:verbatim> <h:message for="address" styleClass="errors" /> </h:panelGroup> <h:outputText value=" "/> <h:commandButton value="sub" image="images/submit_button.gif" action="#{Bean.register}"/> </h:panelGrid> </h:panelGroup> </h:panelGrid> </h:form> </center> </body> </html> </f:view>
welcome page :
If the user enters the correct information in all the fields then user is
informed for the successful registration in the next page.
welcome.jsp :
This is the code for the above page. This is also a simple page in which
only string for successful registration has been shown.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%> <f:view> <html> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <head> <title>Welcome</title> <link href="mycss.css" rel="stylesheet" type="text/css"/> </head> <body ><center> <h:form> <h:panelGrid width="100%" columns="1" border="0" style="padding-left:10px; padding-top:10px; " styleClass="top_bg"> <h:dataTable id="dt1" border="0" cellpadding="0" cellspacing="0" var="ab"> <h:column> <f:facet name="header"> <h:outputText value="RoseIndia" styleClass="style4"/> </f:facet> </h:column> </h:dataTable> </h:panelGrid> <h:panelGrid width="100%" columns="1" border="0" > <f:verbatim> </f:verbatim> <h:outputText value=" "/><h:outputText value=" "/><h:outputText value=" "/> </h:panelGrid> <h:outputText value="Registration is successful." style="color:green; font-weight:bold"/> </h:form> </center> </body> </html> </f:view>
If the user fills incorrect information then messages are rendered like in the figure below :
If the username is already registered with the site then the message that "User is already registered " is shown at the top like in the figure below.
Configuration Files :
Information about message bundle, backing bean, navigation rules are to be specified in the faces-config.xml file. This file has been modified like below :
faces-config.xml :
<?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd" > <faces-config> <application> <locale-config> <default-locale>en</default-locale> </locale-config> <message-bundle>net.roseindia.web.ui.messages</message-bundle> </application> <managed-bean> <managed-bean-name>Bean</managed-bean-name> <managed-bean-class>net.roseindia.web.ui.Bean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>CheckValidUser</managed-bean-name> <managed-bean-class>net.roseindia.web.ui.CheckValidUser</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/pages/login.jsp</from-view-id> <navigation-case> <from-outcome>reg</from-outcome> <to-view-id>/pages/registration.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/pages/successLogin.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/pages/login.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/pages/registration.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/pages/welcome.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/pages/registration.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>
web.xml :
<?xml version="1.0"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- Spring context Configuration Begins--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext-hibernate.xml</param-value> </context-param> <servlet> <servlet-name>context</servlet-name> <servlet-class> org.springframework.web.context.ContextLoaderServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!--End Spring configuration --> <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value> /WEB-INF/faces-config.xml </param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <!-- Extensions Filter --> <filter> <filter-name>extensionsFilter</filter-name> <filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class> <init-param> <param-name>uploadMaxFileSize</param-name> <param-value>100m</param-value> <description>Set the size limit for uploaded files. Format: 10 - 10 bytes 10k - 10 KB 10m - 10 MB 1g - 1 GB </description> </init-param> <init-param> <param-name>uploadThresholdSize</param-name> <param-value>100k</param-value> <description>Set the threshold size - files below this limit are stored in memory, files above this limit are stored on disk. Format: 10 - 10 bytes 10k - 10 KB 10m - 10 MB 1g - 1 GB </description> </init-param> </filter> <filter-mapping> <filter-name>extensionsFilter</filter-name> <url-pattern>*.jsf</url-pattern> </filter-mapping> <filter-mapping> <filter-name>extensionsFilter</filter-name> <url-pattern>/faces/*</url-pattern> </filter-mapping> <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>*.jsf</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Creation of Beans :
Bean.java : This bean has been used for registration page. This bean has properties related to all the fields in the page and setter and getter method corresponding to all the properties. exist property has been used to set true or false value to the "rendered" attribute of the outputText tag responsible for presenting the string "User is already registered". If the username is already present then the value for exist property is set to "true". dao object of HibernateSpringDAO class is used to work with the database.
package net.roseindia.web.ui; import net.roseindia.web.common.*; import net.roseindia.dao.*; import java.util.*; import java.util.regex.*; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; public class Bean{ String userName; String pwd; String confPwd; String email; String address; boolean exist=false; public void setUserName(String userName){ this.userName=userName; } public void setPwd(String pwd){ this.pwd=pwd; } public void setConfPwd(String confPwd){ this.confPwd=confPwd; } public void setEmail(String email){ this.email=email; } public void setAddress(String address){ this.address=address; } public void setExist(boolean exist){ this.exist=exist; } public String getUserName(){ return userName; } public String getPwd(){ return pwd; } public String getConfPwd(){ return confPwd; } public String getEmail(){ return email; } public String getAddress(){ return address; } public boolean getExist(){ return exist; } public String register() throws Exception { String status = "failure"; if (validateData()) { HibernateSpringDAO dao = (HibernateSpringDAO)ServiceFinder.findBean("SpringHibernateDao"); if(dao.checkUser(getUserName())!=null){ exist=true; status = "failure"; }else{ net.roseindia.dao.hibernate.User user = new net.roseindia.dao.hibernate.User(); //Set user name user.setUserName(getUserName()); //Set user Password user.setUserPassword(getPwd()); //Set user Email user.setUserEmail(getEmail()); //Set Address user.setUserAddress(getAddress()); dao.addUser(user); status = "success"; } } return status; } private boolean validateData() { boolean status = true; MessageFactory mf = new MessageFactory(); FacesContext ctx = FacesContext.getCurrentInstance(); //Checking User Name if((userName.length())<4 ){ ctx.addMessage("registerForm:userName", new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage("errorUserName"), null)); status = false; } // End of checking User Name //Checking of Password Length if((pwd.length())<6 ){ ctx.addMessage("registerForm:Password", new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage("errorPasswordLength"), null)); status = false; } if((confPwd.length())<6 ){ ctx.addMessage("registerForm:confirmPassword", new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage("errorPasswordLength"), null)); status = false; } // End of checking Password Length //Checking passwords if (!confPwd.equals(pwd)) { ctx.addMessage("registerForm:confirmPassword", new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage("errorPasswordConfirm"), null)); status = false; } //End of checking passwords //Checking Email address Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(email); boolean matchFound = m.matches(); if (!matchFound) { ctx.addMessage("registerForm:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage("errorEmail"), null)); status = false; } // End of checking Email address return status; } }
CheckValidUser.java
This bean has been used in the login page. All the properties of the bean
are related to the fields of the login page. When the page is submitted then
checkUser() method is called which checks the username and password. If both are
correct then the user is sent to the next page which welcomes the user otherwise
message is displayed to the user in the same login page. In this bean there is
one exist property which is set to true if username or password doesn't match
with the database. So this value is set to the "rendered" property of
the tag responsible for displaying the string "User name or password is
incorrect".
package net.roseindia.web.ui; import net.roseindia.web.common.*; import net.roseindia.dao.*; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; public class CheckValidUser{ String userName; String pwd; boolean exist; public void setUserName(String userName){ this.userName=userName; } public void setPwd(String pwd){ this.pwd=pwd; } public void setExist(boolean exist){ this.exist=exist; } public String getUserName(){ return userName; } public String getPwd(){ return pwd; } public boolean getExist(){ return exist; } public String checkUser() throws Exception { String status = "failure"; HibernateSpringDAO dao = (HibernateSpringDAO)ServiceFinder.findBean("SpringHibernateDao"); if(dao.validateUser(getUserName(),getPwd())!=null){ exist=false; status = "success"; } exist=true; return status; } }
MessageFactory.java :
This java code is used to get the message from message bundle of specific
locale. This class has been used in the Bean class to set the appropriate
message for different fields when the defined condition doesn't meet.
0
package net.roseindia.web.ui; import net.roseindia.web.common.*; import java.util.*; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; public class MessageFactory { ResourceBundle bundle; Locale locale; public MessageFactory() { locale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); bundle = ResourceBundle.getBundle("net.roseindia.web.ui.messages", locale); } public String getMessage(String key) { return bundle.getString(key); } }
Creation of Properties File :
This is the file containing the messages strings that are to be shown in different pages.
# Registration Page errorPasswordConfirm=The passwords are not same. errorUserId=User ID can not be less than 4 characters. errorUserName=User Name can not be less than 4 characters. errorPasswordLength=Password can not be less than 6 characters. errorEmail=Invalid Email Address. already_registered_msg=User is already registered. # Messages.properties file of JSF javax.faces.component.UIInput.REQUIRED=Cannot be blank
creating CSS : 1
body{ background-color:#fff2f2; margin-left:0; margin-right:0; margin-top:0; margin-bottom:0; } .top_bg{ background-image:url(../images/TOP_BG.gif); background-repeat:repeat-x; } .style1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold; font-size: 12px; } .style2 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: bold; } .style3 {font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif;} .style4 { font-family: Verdana, Arial, Helvetica, sans-serif; font-weight:bold; color: #FF0000; } .errors { font-style: italic; color: green; }