Most of web application today having login facilities. This tutorial is giving you a rough idea to develop login application for your application. This login application can be easily integrated with your old application. This login application is based on MVC pattern and build on struts framework. Application is containing three packages actions, model and util. actions package contains all those class which are action class of struts and formbean actionform classes. Model package contain all those classes which are used for logical part and business part. Util package contain only those classes to give helping to application, e.g. Database connection classes, closing object classes and properties file.
Steps to developing user login application
1. Create a project in eclipse
After creating a project in eclipse, now understand the flow of application.
UserAuthAction.java is action class of struts, this class authenticate user’s login and perform action according to the result. This is mainly use for user authentication.
UserAuthAction.java
package com.login.actions; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import com.login.model.UserLogin; public class UserAuthAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean action_perform=false; String action_target; UserLogin u = new UserLogin(); ActionMessages errors_mesg = new ActionMessages(); UserForm uf = (UserForm)form; if(form!=null){ u.setUsername(uf.getUsername()); u.setPassword(uf.getPassword()); action_perform = u.doLogin(); } if(action_perform==false){ errors_mesg.add("submitError", new ActionMessage("errors.login.fail")); saveErrors(request,errors_mesg); action_target="failure"; } else{ action_target="success"; } return mapping.findForward(action_target); } }
UserLogin.java is logical business class, this class checks username and password in database and if matched with database and user enter value, it will throw true in Boolean value.
UserLogin.java
package com.login.model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.login.util.DbUtils; import com.login.util.ConnectionUtils; public class UserLogin extends User{ private static final long serialVersionUID = 1L; public boolean doLogin() throws Exception { PreparedStatement psDoLogin = null; ResultSet rsDoLogin = null; String sqlDoLogin = null; boolean isLoginValidate = false; Connection conn = ConnectionUtils.getConnection(); sqlDoLogin = "Select * from user_registration " + " where sUserID=? and sPassword=password(?)"; psDoLogin = conn.prepareStatement(sqlDoLogin); psDoLogin.setString(1, this.getUsername()); psDoLogin.setString(2, this.getPassword()); rsDoLogin = psDoLogin.executeQuery(); if(rsDoLogin.next()) { isLoginValidate = true; } DbUtils.close(rsDoLogin, psDoLogin, conn); return isLoginValidate; } }
User.java is simple pojo class
User.java
package com.login.model; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private static final long serialVersionUID = 1L; private int id; private int level; private String username; private String password; private Date lastVisit; private Date registrationDate; private String email; private String webSite; private String occupation; private String gender; private String timeZone; private String dateFormat; private int active; private String activationKey; private int deleted; private String firstName; private String lastName; private String ipAddress; private String macAddress; private int failLoginAttempted; public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } public String getDateFormat() { return dateFormat; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } public int getDeleted() { return deleted; } public void setDeleted(int deleted) { this.deleted = deleted; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getFailLoginAttempted() { return failLoginAttempted; } public void setFailLoginAttempted(int failLoginAttempted) { this.failLoginAttempted = failLoginAttempted; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getLastVisit() { return lastVisit; } public void setLastVisit(Date lastVisit) { this.lastVisit = lastVisit; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getRegistrationDate() { return registrationDate; } public void setRegistrationDate(Date registrationDate) { this.registrationDate = registrationDate; } public String getTimeZone() { return timeZone; } public void setTimeZone(String timeZone) { this.timeZone = timeZone; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getWebSite() { return webSite; } public void setWebSite(String webSite) { this.webSite = webSite; } }
UserForm.java is ActionForm class of struts
UserForm.java
package com.login.actions; import org.apache.struts.validator.ValidatorForm; public class UserForm extends ValidatorForm{ private static final long serialVersionUID = 1L; private String username; private String password; 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; } }
ConnectionUtils.java class is used to create database connections
ConnectionUtils.java
package com.login.util; import java.sql.Connection; import java.sql.DriverManager; public class ConnectionUtils { static{ try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { } } public static Connection getConnection() throws Exception { return getDBConnection(); } public static Connection getDBConnection() throws Exception { Connection conn = null; String URLPath="jdbc:mysql://localhost:3306/login_app"; String dbUser="yourUserName"; String dbPassword="yourPassword"; try{ conn = DriverManager.getConnection(URLPath,dbUser, dbPassword); } catch(Exception e) { e.printStackTrace(); } return conn; } }
DbUtils.java class is used for to close database objects which can be resultset, prepareStatement or Connection.
DbUtils.java
package com.login.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DbUtils { public static void close(ResultSet rs, Statement stm) { if (rs != null) { try { rs.close(); } catch (Exception e) { } } if (stm != null) { try { stm.close(); } catch (Exception e) { } } } public static void close(ResultSet rs, Statement stm, Connection conn) { if (rs != null) { try { rs.close(); } catch (Exception e) { } } if (stm != null) { try { stm.close(); } catch (Exception e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } public static void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { } } } public static void close(Statement stm) { if (stm != null) { try { stm.close(); } catch (SQLException e) { } } } public static void close(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } }
struts-config.xml file is used for struts configuration. This xml file contains all details of application in struts form value action mapping
struts-config.xml
<struts-config> <form-beans> <form-bean name="loginform" type="com.login.actions.UserForm"/> </form-beans> <action-mappings> <action path="/doLogin" type="com.login.actions.UserAuthAction" name="loginform" scope="request" validate="true" input="input"> <forward name="input" path="/index.jsp"/> <forward name="success" path="/welcome.jsp"/> <forward name="failure" path="/index.jsp"/> </action> </action-mappings> <controller inputForward="true" /> <message-resources parameter="com.login.util.ApplicationResources"/> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml, /WEB-INF/validation.xml"/> <set-property property="stopOnFirstError" value="true" /> </plug-in> </struts-config>
validation.xml is used for checking validate form value, if form is not validated properly it will throw error on user form.
validation.xml
<form-validation> <formset> <form name="loginform"> <field property="username" depends="required"> <msg name="required" key="errors.login.name"/> </field> <field property="password" depends="required"> <msg name="required" key="errors.login.password"/> </field> <field property="submitError" depends="validwhen"> <msg name="validwhen" key="errors.login.fail" /> <var> <var-name>test</var-name> <var-value>((username!=null) and (password!=null))</var-value> </var> </field> </form> </formset> </form-validation>
ApplicationResources.properties file is used for configuration and error
ApplicationResources.properties
button.login=Login # errors errors.login.fail=Incorrect login parameter errors.login.name=Please fill name errors.login.password=Please fill password
Database table user_registration
CREATE TABLE `login_app`.`user_registration` ( `id` int(10) unsigned NOT NULL auto_increment, `sUserID` varchar(45) NOT NULL, `sPassword` varchar(45) NOT NULL, `sFirstName` varchar(45) default NULL, `sLastName` varchar(45) default NULL, `sEmail` varchar(45) default NULL, `cGender` char(1) default NULL, `sUserGroup` varchar(45) default NULL, `sCreatedDate` datetime default NULL, `cStatus` char(1) default NULL, PRIMARY KEY (`id`), UNIQUE KEY `sUserID` (`sUserID`), UNIQUE KEY `sEmail` (`sEmail`) )
2. Deploy project in tomcat or jBoss
3. Run application in browser
4. Do Login by username admin and password admin



Link to Us