Archive for JSP

Building a User Registration Application

Sunday, December 5th, 2010

User Registration is basic need of any web application. This tutorial will give you a rough idea to create user sign in application. This user registration application can be easily integrated with any existing old application. User Registration is developed on Struts framework and follow MVC pattern. 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 Create user Registration application

UserRegisterForm.java

package com.register.actions;

import org.apache.struts.validator.ValidatorForm;

public class UserRegisterForm extends ValidatorForm{

    private static final long serialVersionUID = 1L;

    private String emailid;
    private String password;
    private String cpassword;
    private String firstname;
    private String lastname;
    private String gender;
    private String submitError;

    public String getSubmitError() {
        return submitError;
    }
    public void setSubmitError(String submitError) {
        this.submitError = submitError;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmailid() {
        return emailid;
    }
    public void setEmailid(String emailid) {
        this.emailid = emailid;
    }
    public String getCpassword() {
        return cpassword;
    }
    public void setCpassword(String cpassword) {
        this.cpassword = cpassword;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}

UserRegistrationAction.java

package com.register.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.register.model.UserRegistration;

public class UserRegistrationAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        boolean action_perform = false;
        String action_target;

        UserRegistration u = new UserRegistration();

        ActionMessages errors_mesg = new ActionMessages();

        UserRegisterForm uf = (UserRegisterForm) form;

        if (form != null) {
            u.setEmail(uf.getEmailid());
            u.setPassword(uf.getPassword());
            u.setFirstName(uf.getFirstname());
            u.setLastName(uf.getLastname());
            u.setGender(uf.getGender());
            action_perform = u.newuserregistration();

            String sError=u.getDbError();
            if(sError.equalsIgnoreCase("error"))
            {
                errors_mesg.add("submitError",
                    new ActionMessage("errors.user.registration.email.duplicate"));
                saveErrors(request,errors_mesg);
            }
        }

        if (action_perform == false) {
            errors_mesg.add("submitError",
                    new ActionMessage("errors.user.registration.fail"));
            saveErrors(request, errors_mesg);
            action_target = "failure";
        } else {
            errors_mesg.add("submitError",
                    new ActionMessage("errors.user.registration.success"));
            saveErrors(request, errors_mesg);
            action_target = "success";
        }

        return mapping.findForward(action_target);
    }
}

User.java

package com.register.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 password;
    private String cpassword;
    private String forgetpassword;
    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;
    private String dbError="";
    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 getWebSite() {
        return webSite;
    }
    public void setWebSite(String webSite) {
        this.webSite = webSite;
    }
    public String getForgetpassword() {
        return forgetpassword;
    }
    public void setForgetpassword(String forgetpassword) {
        this.forgetpassword = forgetpassword;
    }
    public String getCpassword() {
        return cpassword;
    }
    public void setCpassword(String cpassword) {
        this.cpassword = cpassword;
    }
    public String getDbError() {
        return dbError;
    }
    public void setDbError(String dbError) {
        this.dbError = dbError;
    }

}

UserRegistration.java

package com.register.model;

import java.sql.Connection;
import java.sql.PreparedStatement;

import com.register.util.ConnectionUtils;
import com.register.util.DbUtils;

public class UserRegistration extends User{

    private static final long serialVersionUID = 1L;

    public boolean newuserregistration() throws Exception
    {
        PreparedStatement psUserRegistration = null;
        String sqlUserRegistration = null;

        boolean isRegistered = false;

        Connection conn = ConnectionUtils.getConnection();

        sqlUserRegistration = "insert into user_master(sEmail, sPassword, sFirstName," +
                              " sLastName, cGender, iUserType, sCreatedDate, cStatus)" +
                              " values(?,md5(?),?,?,?,1,sysdate(),'A')";

        try{
            psUserRegistration = conn.prepareStatement(sqlUserRegistration);
            psUserRegistration.setString(1, this.getEmail());
            psUserRegistration.setString(2, this.getPassword());
            psUserRegistration.setString(3, this.getFirstName());
            psUserRegistration.setString(4, this.getLastName());
            psUserRegistration.setString(5, this.getGender());
            psUserRegistration.executeUpdate();

            isRegistered=true;
        }
        catch(Exception e)
        {
            String errorMessage=e.getMessage();
            e.printStackTrace();
            if(errorMessage.indexOf("Duplicate entry")>=0)
            {
                this.setDbError("error");
            }
            isRegistered=false;
            e.printStackTrace();
        }
        DbUtils.close(psUserRegistration, conn);

        return isRegistered;
    }
}

ConnectionUtils.java

package com.register.util;

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.struts.util.MessageResources;

public class ConnectionUtils {

    private static MessageResources messages
     = MessageResources.getMessageResources("com.register.util.ApplicationResources");
    private static String USER_NAME_DB=messages.getMessage("db.user");
    private static String USER_PASSWORD_DB=messages.getMessage("db.password");
    private static String DB_NAME=messages.getMessage("db.dbname");
    private static String HOST_NAME=messages.getMessage("db.host");

    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 URL="jdbc:mysql://"+HOST_NAME+":3306/"+DB_NAME;
          try{
              conn = DriverManager.getConnection(URL,USER_NAME_DB, USER_PASSWORD_DB);
          }
          catch(Exception e)
          {
              e.printStackTrace();
          }

          return conn;
      }
}

DbUtils.java

package com.register.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
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(PreparedStatement ps, Connection conn)
    {
        if (ps != null) {
            try {
                ps.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

<!DOCTYPE struts-config PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

    <struts-config>

        <form-beans>
            <form-bean name="registerform" type="com.register.actions.UserRegisterForm"/>
        </form-beans>

        <action-mappings>
            <action
                path="/doRegister"
                type="com.register.actions.UserRegistrationAction"
                name="registerform"
                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.register.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="registerform">
           <field property="emailid" depends="required,email">
            <msg name="required" key="errors.user.registration.email"/>
            <msg name="email" key="errors.user.registration.email.valid"/>
           </field>
           <field property="password" depends="required">
            <msg name="required" key="errors.user.registration.password"/>
           </field>
           <field property="cpassword" depends="required,validwhen">
            <msg name="required" key="errors.user.registration.password.confirm"/>
            <msg name="validwhen" key="errors.user.registration.password.match" />
               <var>
                  <var-name>test</var-name>
                  <var-value>(password==cpassword)</var-value>
               </var>
           </field>
           <field property="firstname" depends="required">
            <msg name="required" key="errors.user.registration.first.name"/>
           </field>
           <field property="lastname" depends="required">
            <msg name="required" key="errors.user.registration.last.name"/>
           </field>
           <field property="gender" depends="required">
            <msg name="required" key="errors.user.registration.gender"/>
           </field>
           <field property="submitError" depends="validwhen">
             <msg name="validwhen" key="errors.user.registration.fail" />
           <var>
              <var-name>test</var-name>
               <var-value>((emailid!=null) and ((password!=null) and ((cpassword!=null) and ((firstname!=null) and ((lastname!=null) and (gender!=null))))))</var-value>
           </var>
          </field>
        </form>
  </formset>

</form-validation>

ApplicationResources.properties file is used for configuration and error

ApplicationResources.properties

button.register=Register

# Database configuration setting
db.user=root
db.password=
db.host=localhost
db.dbname=reg_app

# errors

errors.user.registration.first.name=First Name cannot left empty
errors.user.registration.last.name=Last Name cannot left empty
errors.user.registration.password=Password cannot left empty
errors.user.registration.password.confirm=Confirm Password cannot left empty
errors.user.registration.password.match=Password & Confirm password is not matched
errors.user.registration.email=Email cannot left empty
errors.user.registration.email.valid=Enter Valid Email ID e.g. myemailid@gmail.com
errors.user.registration.email.duplicate=Duplicate Email Found
errors.user.registration.gender=Select Gender

errors.user.registration.fail=Error found while registration user
errors.user.registration.success=Thank you for registration

Database table user_master

CREATE TABLE `user_master` (
  `iUID` int(10) unsigned NOT NULL auto_increment,
  `sEmail` varchar(255) default NULL,
  `sPassword` varchar(45) NOT NULL,
  `sFirstName` varchar(45) default NULL,
  `sLastName` varchar(45) default NULL,
  `cGender` char(1) default NULL,
  `iUserType` int(10) unsigned default NULL,
  `sForgetPassword` varchar(45) default NULL,
  `sCreatedDate` datetime default NULL,
  `sLastLogin` datetime default NULL,
  `cStatus` char(1) default NULL,
  PRIMARY KEY  (`iUID`),
  UNIQUE KEY `sEmail` (`sEmail`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

JSP files
index.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<html:html lang="true">
<head>
<title>User Registration Application</title>
</head>

<body>
<html:errors property="submitError"/>

<html:form action="doRegister">
        Email: <html:text property="emailid" /> <html:errors property="emailid"/><br>
        Password: <html:password property="password" /> <html:errors property="password"/><br>
        Confirm Password: <html:password property="cpassword" /> <html:errors property="cpassword"/><br>
        First Name: <html:text property="firstname" /> <html:errors property="firstname"/><br>
        Last Name: <html:text property="lastname" /> <html:errors property="lastname"/><br>
        Gender: <html:select property="gender">
        <html:option value="">Select Gender</html:option>
        <html:option value="M">Male</html:option>
        <html:option value="F">Female</html:option>
        </html:select>
        <html:errors property="gender"/><br>
        <html:submit><bean:message key="button.register"/></html:submit>
</html:form>
</body>
</html:html>

welcome.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html>
<head>
<title>Welcome Registered successfully</title>
</head>

<body>
<html:errors property="submitError"/>
</body>
</html>

2. Deploy project in tomcat or jBoss

3. Run application in browser

Download User Registration application