Struts Login Form Example Eclipse MySql Apache Tomcat

Struts Login Example

Struts 1.3 Java Eclipse MySql Apache Tomcat

Project Screenshot:



Project Explorer:



Source code:

struts-config.xml 
<?xml version="1.0" encoding="UTF-8"?>

<!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-beans>
        
        <form-bean name="loginForm" type="com.loginexample.forms.LoginForm"/>

    </form-beans>

    <!-- Action Mappings -->
    <action-mappings>

     <action name="loginForm" path="/Login" type="com.loginexample.actions.LoginAction" scope="request" input="/Login.jsp">
         <forward name="failure" path="/Failure.jsp" redirect="true"/>
         <forward name="success" path="/Success.jsp" redirect="true"/>
     </action>

    </action-mappings>
    
    <!-- Message Source -->
     <message-resources parameter="com.loginexample.resources.Application"/>

</struts-config>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>StrutsLoginFormExample</display-name>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>
          /WEB-INF/struts-config.xml
       </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<%@taglib prefix="logic" uri="http://struts.apache.org/tags-logic"%>
<%@taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><bean:message key="loginform.label.title"/></title>
</head>
<body>
<center>
<h1><bean:message key="loginform.label.title"/></h1>
<html:form action="/Login" focus="username">
<table>
<tr><td>
 <bean:message key="loginform.label.usernane"/>
 </td>
 <td>
   <html:text property="username"/>
  </td>
  <td>
  <logic:messagesPresent property="username">
   <html:messages id="error" property="username">
    <font color="red"><bean:write name="error"/></font>
   </html:messages>
  </logic:messagesPresent>
 </td></tr>
<tr><td>
  <bean:message key="loginform.label.password"/>
 </td>
 <td>
  <html:password property="paswd"/>
 </td>
 <td> 
 <logic:messagesPresent property="paswd">
  <html:messages id="error" property="paswd">
   <font color="red"><bean:write name="error"/></font>
  </html:messages>
 </logic:messagesPresent>
 </td></tr>
<tr><td></td>
  <td align="left">
 <html:submit value="Login"/>
 <html:reset value="Cancel"/>
 </td>
  <td>
 </td></tr>
</table>
</html:form>
</center>
</body>
</html>

Success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Successful</title>
</head>
<body>
 <h1>Login Successful</h1>
</body>
</html>

Failure.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Failure</title>
</head>
<body>
 <h1 style="color: red;">Login Failure</h1>
</body>
</html>

LoginForm.java
package com.loginexample.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class LoginForm extends ActionForm {


 /**
  * nn
  */
 private static final long serialVersionUID = 1L;
 private String username = null;
 private String paswd = null;
 
 public String getUsername() {
  return username;
 }
 
 public void setUsername(String username) {
  this.username = username;
 }
 
 public String getpaswd() {
  return paswd;
 }
 
 public void setpaswd(String paswd) {
  this.paswd = paswd;
 }
 
 @Override
 public void reset(ActionMapping mapping, HttpServletRequest request) {
  this.paswd = null;
 }
 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if(username==null || username.length()==0 || username.trim().equals(""))
  {
   ActionMessage message = new ActionMessage("loginform.username.empty");
   errors.add("username", message);
  }
  else if(!username.matches("^[a-zA-Z0-9 ]+$"))
  {
   errors.add("username", new ActionMessage("loginform.username.alphabets"));
  }
  else if(username.length()<3)
  {
   errors.add("username", new ActionMessage("loginform.username.length"));
   
  }
  if(paswd==null||paswd.length()==0||paswd.trim().equals(""))
  {
   errors.add("paswd", new ActionMessage("loginform.paswd"));
  }
  
 
 return errors;
 }
 

}


LoginAction,java
package com.loginexample.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 com.loginexample.forms.LoginForm;
import com.loginexample.services.LoginService;

public class LoginAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  LoginForm loginForm = (LoginForm)form;
  LoginService loginService= new LoginService();
  
  try
  {
   loginService.checkLogin(loginForm);
   return mapping.findForward("success");
  }
  catch (Exception e)
  {
   return mapping.findForward("failure");
  }
 
 }

}


LoginService.java
package com.loginexample.services;

import java.sql.SQLException;

import com.loginexample.dao.impl.LoginDaoImplementation;
import com.loginexample.exceptions.InvalidUserException;
import com.loginexample.forms.LoginForm;

public class LoginService {
 public boolean checkLogin(LoginForm loginForm) throws SQLException, InvalidUserException
 {
  LoginDaoImplementation loginDao= new LoginDaoImplementation();
  if(!loginDao.checkLogin(loginForm))
    throw new InvalidUserException("Incorrect Username/Password.");
  else
   return true;
 }

}


LoginDao.java
package com.loginexample.dao;

import java.sql.SQLException;

import com.loginexample.forms.LoginForm;

public interface LoginDao 
{
public boolean checkLogin(LoginForm loginForm) throws SQLException;
}


LoginDaoImplementation.java
package com.loginexample.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.loginexample.dao.LoginDao;
import com.loginexample.forms.LoginForm;
import com.loginexample.utilities.DBUtilities;

public class LoginDaoImplementation implements LoginDao
{
 public boolean checkLogin(LoginForm loginForm) throws SQLException
 {
  Connection con=null;
  boolean access=false;
  
  try
  {
   con=DBUtilities.getConnection();
   
   String query= "select * from login where username=? and password=?";
   PreparedStatement stmt= con.prepareStatement(query);
   stmt.setString(1, loginForm.getUsername());
   stmt.setString(2, loginForm.getpaswd());
   ResultSet rs= stmt.executeQuery();
   
   if(rs.next())
   {
    access=true;
   }
  
   
  }
  finally
  {
   DBUtilities.closeConnection(con);
  }
  return access;
 }
}



DBUtilities.java
package com.loginexample.utilities;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtilities {
 
    public static Connection getConnection()
    {
     Connection con = null;
     
     try 
     {
    Class.forName("com.mysql.jdbc.Driver");
    con  =DriverManager.getConnection("jdbc:mysql://localhost:3306/nn","root","");
     } 
     catch (ClassNotFoundException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     } 
     catch (SQLException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     }
     
     return con; 
     
    }
 
     public static void closeConnection(Connection con){      
      if(con!=null){
       try{
       con.close();
       }catch(SQLException e){}
      }      
     }   
       public static void closePreparedStatement(PreparedStatement ps){      
      if(ps!=null){
       try{
       ps.close();
       }catch(SQLException e){}
      }
      
     }

}



InvalidUserException.java
package com.loginexample.exceptions;

public class InvalidUserException extends Exception
{

 /**
  * 
  */
 private static final long serialVersionUID = 1L;

 public InvalidUserException(String arg0) 
 {
  super(arg0);
 }
 

 
}


Application.properties
loginform.label.title=Login Form
loginform.label.usernane=Username : 
loginform.label.password=Password : 
loginform.username.empty=Please enter username
loginform.username.alphabets=Please enter alphabets only
loginform.username.length=Please enter username of length of at least 3 characters
loginform.paswd=Please enter password



Download:
StrutsLoginFormExample

Registration Form - Struts 1.3 Example - Eclipse - MySQL - Apache Tomcat

Simple Struts Example: Registration Form

Struts 1.3 - Java - MySQL- Eclipse - Apache Tomcat




Project Screenshots:




Project Explorer:



Source code:

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!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="registrationForm" type="com.loginexample.forms.RegistrationForm"/>

    </form-beans>

    
    <action-mappings>

     <action name="registrationForm" path="/register" type="com.loginexample.actions.RegistrationAction" scope="request" input="/Register.jsp">
         <forward name="failure" path="/Failure.jsp" redirect="true"/>
         <forward name="success" path="/Success.jsp" redirect="true"/>
     </action>

    </action-mappings>
     

</struts-config>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>StrutsLoginFormExample</display-name>
  <!-- WWW.2K8618.BLOGSPOT.COM -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>
          /WEB-INF/struts-config.xml
       </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"   pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Form</title>
</head>
<body>
<center>
<h1>Registration Form </h1>
<html:form action="/register" >
 Username : <html:text property="username"/><br/>
 <br/>
 Password : <html:password property="paswd"/><br/>
 <br/>
 <html:submit value="Register" />
</html:form>
</center>
</body>
</html>

RegistrationForm.java
package com.loginexample.forms;

import org.apache.struts.action.ActionForm;


public class RegistrationForm extends ActionForm
{
  /**
  * 
  */
 private static final long serialVersionUID = 1L;
  private String username = null;
  private String paswd = null;
  
  public String getUsername() {
   return username;
  }
  
  public void setUsername(String username) {
   this.username = username;
  }
  
  public String getpaswd() {
   return paswd;
  }
  
  public void setpaswd(String paswd) {
   this.paswd = paswd;
  }
}

RegistrationAction.java
package com.loginexample.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 com.loginexample.forms.RegistrationForm;
import com.loginexample.services.LoginService;

public class RegistrationAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  RegistrationForm regForm=(RegistrationForm) form;
  LoginService loginService= new LoginService();
  
  try
  {
   if(loginService.addLogin(regForm))
    return mapping.findForward("success");
   else
    return mapping.findForward("failure");
  }
  catch (Exception e)
  {
   return mapping.findForward("failure");
  }
 
 }

}


LoginService.java
package com.loginexample.services;

import java.sql.SQLException;

import com.loginexample.dao.impl.LoginDaoImplementation;
import com.loginexample.forms.RegistrationForm;

public class LoginService {
 LoginDaoImplementation loginDao= new LoginDaoImplementation();
 
 public boolean addLogin(RegistrationForm regForm) throws SQLException
 {
  if(loginDao.addLogin(regForm))
   return true;
  else
   return false;
 }
}


LoginDao.java
package com.loginexample.dao;

import java.sql.SQLException;

import com.loginexample.forms.RegistrationForm;

public interface LoginDao 
{
 public boolean addLogin(RegistrationForm regForm) throws SQLException;
}


LoginDaoImplementation.java
package com.loginexample.dao.impl;

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

import com.loginexample.dao.LoginDao;
import com.loginexample.forms.RegistrationForm;
import com.loginexample.utilities.DBUtilities;

public class LoginDaoImplementation implements LoginDao
{
 public boolean addLogin(RegistrationForm regForm) throws SQLException
 {
  Connection con=null;
  boolean access=false;
  
  try
  {
   con=DBUtilities.getConnection();
   
   String query= "insert into login values (?,?)";
   PreparedStatement stmt= con.prepareStatement(query);
   stmt.setString(1, regForm.getUsername());
   stmt.setString(2, regForm.getpaswd());
   int result= stmt.executeUpdate();
   
   if(result>0)
   {
    access=true;
   }
  }
  finally
  {
   DBUtilities.closeConnection(con);
  }
  return access;
 }
}


DBUtilities.java
package com.loginexample.utilities;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtilities {
 
    public static Connection getConnection()
    {
     Connection con = null;
     
     try 
     {
    Class.forName("com.mysql.jdbc.Driver");
    con  =DriverManager.getConnection("jdbc:mysql://localhost:3306/nn","root","nn");
     } 
     catch (ClassNotFoundException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     } 
     catch (SQLException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     }
     
     return con; 
     
    }
 
     public static void closeConnection(Connection con){      
      if(con!=null){
       try{
       con.close();
       }catch(SQLException e){}
      }      
     }   
       public static void closePreparedStatement(PreparedStatement ps){      
      if(ps!=null){
       try{
       ps.close();
       }catch(SQLException e){}
      }
      
     }

}


Success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Successful</title>
</head>
<body>
<center>
 <h1>Registration Successful</h1>
</center> 
</body>
</html>

Failure.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Failure</title>
</head>
<body>
<center>
 <h1 style="color: red;">Registration Failed.</h1>
</center>
</body>
</html>


MySql Database
mysql> desc login;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) | YES  |     | NULL    |       |
| password | varchar(25) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.06 sec)



Download: StrutsExampleRegistration

JSP PreparedStatement Example - Login -Java - Eclipse - Apache Tomcat

Java Login Example 
JSP - PreparedStatement - MySQL- Eclipse - Apache Tomcat 

Notes:

  • PreparedStatement can be used to prevent sql injection.

Project:



Project Explorer:


Source code:


LoginDao.java
package com.login.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.login.model.Login;
import com.login.utilities.DBUtilities;

public class LoginDao 
{
 public boolean checkLogin(Login login) throws SQLException
 {
  Connection con=null;
  try{
 
  con=DBUtilities.getConnection();
  
  String query="select * from sec_login where username=? and password=?";
  PreparedStatement pst= con.prepareStatement(query);
  pst.setString(1, login.getUsername());
  pst.setString(2, login.getPassword());
  ResultSet rs= pst.executeQuery();
 
  if(rs.next())
  {
   return true;
  }
  else 
  {
   return false;
  }
   
  }
  finally{
   DBUtilities.closeConnection(con);
  }
 }
 
}


DBUtilities.java
package com.login.utilities;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtilities {
 
    public static Connection getConnection(){
     Connection con = null;
     
     try {
   Class.forName("com.mysql.jdbc.Driver");
   con  =DriverManager.getConnection("jdbc:mysql://localhost:3306/nn","root","nn");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    return con; 
     
    }
 
     public static void closeConnection(Connection con){      
      if(con!=null){
       try{
       con.close();
       }catch(SQLException e){}
      }      
     }   
       public static void closePreparedStatement(PreparedStatement ps){      
      if(ps!=null){
       try{
       ps.close();
       }catch(SQLException e){}
      }
      
     }

}



LoginManagement.java
package com.login.model;

import java.sql.SQLException;
import com.login.dao.LoginDao;

public class LoginManagement 
{

 LoginDao logindao= new LoginDao();
 public boolean checkLogin(Login login) throws SQLException
 {
  return logindao.checkLogin(login);
 }

 
}



LoginController.java
package com.login.controller;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.login.model.Login;
import com.login.model.LoginManagement;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doPost(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  LoginManagement loginManagement = new LoginManagement();
  RequestDispatcher rd= null;
  String action=request.getParameter("actiontype");
  if(action.equals("Login"))
  {
   
   String username=request.getParameter("username");
   String password= request.getParameter("password");
   Login login= new Login(username, password);
   boolean result=false;
   try {
     result = loginManagement.checkLogin(login);
     if(result)
     {
      request.setAttribute("user", login.getUsername());
      rd=request.getRequestDispatcher("Home.jsp");
      rd.forward(request, response);
      return;
     }
     else
     {
      request.setAttribute("err", "err");
      rd=request.getRequestDispatcher("Login.jsp");
      rd.forward(request, response);
      return;
     }
   } catch (SQLException e) {
    request.setAttribute("err", "err");
    rd=request.getRequestDispatcher("Login.jsp");  
    rd.forward(request, response);
    return;
   } 
  }
  

 }

}



Login.java
package com.login.model;

public class Login 
{

 private String username;
 private String password;
 
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public Login(String username, String password) {
  super();
  this.username = username;
  this.password = password;
 }
 
 
}



Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log in</title>
<script type="text/javascript">
function validateForm()
{
 
 var x=document.getElementById("username");
 if (x.value=="")
   {
  
  document.getElementById('username_innermsg').innerHTML="Please enter the Username.";
    x.focus();
  return false;
   }
 
 document.getElementById('username_innermsg').innerHTML='';
 var x=document.getElementById("password");
 if (x.value=="")
   {
  
  document.getElementById('password_innermsg').innerHTML="Please enter the Password.";
    x.focus();
  return false;
   }
 
 document.getElementById('password_innermsg').innerHTML='';
}

</script>

</head>
<body>
<center>
<h1>Log in</h1>
<form action="LoginController" method="post" onsubmit="return validateForm();">
<input type="hidden" name="actiontype" value="Login">
<table >
<tr>
<td>User Name :</td><td><input type="text" name="username" id="username"></td><td width="200px"> <i style="color: red;" id="username_innermsg"></i></td>

</tr>
<tr>
<td>Password :</td><td><input type="password" name="password" id="password"></td><td width="200px"> <i style="color: red;" id="password_innermsg"></i></td>
</tr>
<tr><td></td><td  ><input type="submit" value="Login"><input type="reset" value="Cancel"></td><td ></td> </tr>
</table>


</form>
<i  style="color: red;">
<%
String er=null;
try{
 er= (String)request.getAttribute("err");
 if(er.equals("err"))
 {
  out.print("Incorrect Username/Password."); 
 }
}
catch (Exception e){
 
}

%>
</i>
</center>
</body>
</html>


Home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<%
String user =(String)request.getAttribute("user");

%>
welcome <%if(user!=null) out.print(user); %>..
<center>
<h1>You are logged in.</h1>

</center>
</body>
</html>

Download Project: SecureLoginUsingPreparedStatement

Log User Activities - Java Log4j - HTML - Apache - Eclipse - Log in Example



Log User Activities
Java-Log4j - HTML - Apache - Eclipse

Logging example:


22-06-2013 13:53:32 INFO  LogInController:33 - 2K8CSE logs in.
22-06-2013 13:54:02 ERROR LogInController:40 - 2K8CSE failed to log in.
22-06-2013 13:54:16 ERROR LogInController:40 - ABCD failed to log in.

Screen shots:

After successful Log in:

Welcome to home page.


Steps: 
1. Add log4j-1.2.16 jar file to the project.




2. Add log4j.properties to the project.

# Root logger option
log4j.rootLogger=INFO, file, stdout
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\Users\\nn\\Desktop\\nnEclipse4\\UserAuditExample\\systemlog.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n

3. In LogInController (controller, servlet) add the following code in constructor.
 Logger log = Logger.getLogger(LogInController.class);

4. Add the following code to log the information to the log file.
log.info(message);
eg:
log.info(username+" logs in.");
log.error(username+" failed to log in.");

Project Explorer:


login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log in</title>
<script type="text/javascript">
function validateForm()
{
 
 var x=document.getElementById("username");
 if (x.value=="")
   {
  
  document.getElementById('username_innermsg').innerHTML="Please enter the User Name.";
    x.focus();
  return false;
   }
 
 document.getElementById('username_innermsg').innerHTML='';
 var x=document.getElementById("paswd");
 if (x.value=="")
   {
  
  document.getElementById('password_innermsg').innerHTML="Please enter the Password.";
    x.focus();
  return false;
   }
 
 document.getElementById('password_innermsg').innerHTML='';
}

function resetInnerHtmlMsgs() {
 document.getElementById('username_innermsg').innerHTML='';
 document.getElementById('password_innermsg').innerHTML=''; 
}
</script>

</head>
<body>
<center>
<h1>Log in</h1>
<form  action="LogInController" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td>User Name :</td><td><input type="text" name="username" id="username"></td><td width="200px"> <i style="color: red;" id="username_innermsg"></i></td>
</tr>
<tr>
<td>Password :</td><td><input type="password" name="paswd" id="paswd"></td><td width="200px"> <i style="color: red;" id="password_innermsg"></i></td>
</tr>
<tr><td><input type="submit" value="Login"></td><td><input type="reset" value="Cancel" onclick="resetInnerHtmlMsgs()"/></td></tr>
</table>
</form>
</center>
</body>
</html>

LogInController.java

 package com.logexample.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.logexample.model.LogIn;

@WebServlet("/LogInController")
public class LogInController extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private Logger log;
       public LogInController() {
        super();
        log = Logger.getLogger(LogInController.class);
     }
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  LogIn login= new LogIn("2K8CSE", "Password@123");
  RequestDispatcher rd= null;
  String username= request.getParameter("username");
  String password=request.getParameter("paswd");
  if(username.equals(login.getUsername())&&password.equals(login.getPassword()))
  {
   log.info(username+" logs in.");
   rd=request.getRequestDispatcher("success.html");
   rd.forward(request, response);
   return;
  }
  else
  {
   log.error(username+" failed to log in.");
   rd=request.getRequestDispatcher("error.html");
   rd.forward(request, response);
   return;
  }
 }

}

Login.java
package com.logexample.model;

public class LogIn {
 private String username;
 private String password;
 public LogIn(String username, String password) {
  super();
  this.username = username;
  this.password = password;
 }
 public LogIn() {
  super();
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 

}

success.html
 <html>
<head>
<title>Home</title>
</head>
<body>
<center><br/><br/>
<h2>Welcome to home page.</h2>
</center>
</body>
</html>

Download: UserAuditExample

Stored Procedure - Java - MySQL -Login Example - Eclipse



Log in Example Using Stored Procedure 
Java - MySQL - Eclipse


 Project Explorer:


Database Table: sec_login
mysql> desc sec_login;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) | YES  |     | NULL    |       |
| password | varchar(30) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql>

Stored Procedure: checklogin()
delimiter //
create procedure checklogin(in user varchar(20), in pass varchar(30))
begin

select * 
from sec_login 
where username=user AND password=pass;

end
//
delimiter ;
LoginDao.java
package com.login.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.login.model.Login;
import com.login.utilities.DBUtilities;

public class LoginDao 
{

 public boolean checkLogin(Login login) throws SQLException
 {
  Connection con=null;
  CallableStatement callableStatement = null;
  try{
 
  con=DBUtilities.getConnection();
  String dbCheckLogin = "{call checklogin(?,?)}";
  callableStatement = con.prepareCall(dbCheckLogin);
  callableStatement.setString(1, login.getUsername());
  callableStatement.setString(2, login.getPassword());
  ResultSet rs= callableStatement.executeQuery();
  
  if(rs.next())
  {
   return true;
  }
  else 
  {
   return false;
  }
   
  }
  finally{
   DBUtilities.closeConnection(con);
  }
 }
 
}

LoginManagement.java
package com.login.model;

import java.sql.SQLException;
import com.login.dao.LoginDao;

public class LoginManagement 
{

 LoginDao logindao= new LoginDao();
 public boolean checkLogin(Login login) throws SQLException
 {
  return logindao.checkLogin(login);
 }

 
}

LoginController.java
package com.login.controller;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.login.model.Login;
import com.login.model.LoginManagement;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doPost(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  LoginManagement loginManagement = new LoginManagement();
  RequestDispatcher rd= null;
  String action=request.getParameter("actiontype");
  if(action.equals("Login"))
  {
   
   String username=request.getParameter("username");
   String password= request.getParameter("password");
   Login login= new Login(username, password);
   boolean result=false;
   try {
     result = loginManagement.checkLogin(login);
     if(result)
     {
      request.setAttribute("user", login.getUsername());
      rd=request.getRequestDispatcher("Home.jsp");
      rd.forward(request, response);
      return;
     }
  else
  {
   request.setAttribute("err", "err");
   rd=request.getRequestDispatcher("Login.jsp");
   rd.forward(request, response);
   return;
  }
   } catch (SQLException e) {
    request.setAttribute("err", "err");
    rd=request.getRequestDispatcher("Login.jsp");  
    rd.forward(request, response);
    return;
   } 
  }
  

 }

}

Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log in</title>
<script type="text/javascript">
function validateForm()
{
 
 var x=document.getElementById("username");
 if (x.value=="")
   {
  
  document.getElementById('username_innermsg').innerHTML="Please enter the Username.";
    x.focus();
  return false;
   }
 
 document.getElementById('username_innermsg').innerHTML='';
 var x=document.getElementById("password");
 if (x.value=="")
   {
  
  document.getElementById('password_innermsg').innerHTML="Please enter the Password.";
    x.focus();
  return false;
   }
 
 document.getElementById('password_innermsg').innerHTML='';
}

</script>

</head>
<body>
<center>
<h1>Log in</h1>
<form action="LoginController" method="post" onsubmit="return validateForm();">
<input type="hidden" name="actiontype" value="Login">
<table >
<tr>
<td>Username :</td><td><input type="text" name="username" id="username"></td><td width="200px"> <i style="color: red;" id="username_innermsg"></i></td>

</tr>
<tr>
<td>Password :</td><td><input type="password" name="password" id="password"></td><td width="200px"> <i style="color: red;" id="password_innermsg"></i></td>
</tr>
<tr><td></td><td  ><input type="submit" value="Login"><input type="reset" value="Cancel"></td><td ></td> </tr>
</table>


</form>
<i  style="color: red;">
<%
String er=null;
try{
 er= (String)request.getAttribute("err");
 //out.print(er);
 if(er.equals("err"))
 {
  out.print("Username/Password not correct"); 
 }
}
catch (Exception e){
 
}

%>
</i>
</center>
</body>
</html>


Download project: SecureLoginUsingStoredProcedure

Stored Procedure MySQL Example

MySQl Stored Procedure Example

Table:


mysql> desc employees;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| empid     | int(11)     | YES  |     | NULL    |       |
| name   | varchar(20) | YES  |     | NULL    |       |
| salary | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.02 sec)

mysql>

mysql> select * from employees order by id;
+------+-----------+--------+
| id   | name      | salary |
+------+-----------+--------+
|  100 | Ramu      |  10000 |
|  101 | Santhosh  |  15000 |
|  102 | Pratheesh |  16000 |
|  103 | Vasudevan |  20000 |
|  104 | Sajeevan  |  25000 |
+------+-----------+--------+
5 rows in set (0.02 sec)

mysql>


Stored Procedure getsalary() - gets name and salary for the given id.

delimiter //
create procedure getsalary(IN id INT)
begin
select name, salary
from employees
where empid=id;
end
//
delimiter ;

Defining Stored Procedure in MySQL:

mysql> delimiter //
mysql> create procedure getsalary(IN id INT)
    -> begin
    -> select name, salary
    -> from employees
    -> where empid=id;
    -> end
    -> //
Query OK, 0 rows affected (0.04 sec)

mysql> delimiter ;

Calling Stored Procedure

mysql> call getsalary(102);
+-----------+--------+
| name      | salary |
+-----------+--------+
| Pratheesh |  16000 |
+-----------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql>

Notes:

DELIMITER statement is used to change the standard delimiter(;) to another, in this case the delimiter is changed to //.


Declaring Variables

DECLARE variablename datatype DEFAULT initialvalue;

delimiter //
create procedure gettotalsalary()
begin
DECLARE totalsalary int DEFAULT 0; 
select sum(salary) into totalsalary
from employees;
select totalsalary;
end
//
delimiter ;

mysql> call gettotalsalary;
+-------------+
| totalsalary |
+-------------+
|       86000 |
+-------------+
1 row in set (0.03 sec)

Query OK, 0 rows affected (0.03 sec)

mysql> 


Parameters
The parameter has one of three modes IN, OUT and INOUT.

IN -parameter to input.
OUT-parameter to output.
INOUT -shared parameter.

Conditional Control

IF expression THEN commands
ELSEIF expression THEN commands
ELSE commands
END IF; 

CASE
WHEN expression THEN commands

WHEN expression THEN commands
ELSE commands
END CASE;

WHILE loop

WHILE expression DO
Statements
END WHILE

REPEAT loop - equivalent to do while loop in c.

REPEAT
statements;
UNTIL expression
END REPEAT

LEAVE - equivalent to BREAK in c.
   
ITERATE - equivalent to CONTINUE in c.

Reverse of a String and Number of Vowels - Java Program - Scanner


Reverse of a String and Number of Vowels  
 Scanner -Java Program
Program: Reverse.java
import java.util.Scanner;
class Reverse 
{
public static void main(String args[])
{
 String string,reverseString = "";
 int vowelCount=0;
 
   Scanner sc=new Scanner(System.in);
   System.out.print("Enter the word: ");
   string= sc.nextLine();
   
   for(int i=string.length()-1;i>=0;i--)
   {
    char ch=string.charAt(i);
    reverseString+=ch;
    if(ch=='A'||ch=='a'||ch=='E'||ch=='e'||ch=='I'||ch=='i'||ch=='O'||ch=='o'||ch=='U'||ch=='u')
    vowelCount++;
   }
   
   
   System.out.println("Reverse: "+reverseString+"\nNumber of vowels: "+vowelCount);
   
}
}

Output:
Enter the word: 2k8cse
Reverse: esc8k2
Number of vowels: 1

Form Validation Using InnerHTML - HTML JAVASCRIPT



FORM VALIDATION USING INNERHTML
HTML JAVASCRIPT

Demo Registration Form

Male Female


* - Mandatory
HTML CODE: REGISTRATION.HTML
<html >
<head>

<!--validation-->
<script typ="text/javascript" src="innerHTMLValidation.js" ></script>
     
</head>

<body>
<div class="container">
<div class="content">
 <center>
<form name="form1"  method="post" action="success.html">
 <fieldset>

<h1>Demo Registration Form</h1>
   <table border='0'>
 <tr>
  <td><LABEL for="firstname">First Name:<sup style="color:#F00">*</sup> </LABEL></td>
         <td><INPUT type="text" id="firstname"></td><td width="200px"><i style="color:red;" id="pointfn"></i></td>
 </tr>
 <tr>
  <td><LABEL for="lastname">Last Name:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><INPUT type="text" id="lastname"></td><td width="200px"><i style="color:red;" id="pointln"></i></td>
 </tr>
     
 <tr>
   <td><LABEL for="gender">Gender:<sup style="color:#F00">*</sup> </LABEL></td> <td><INPUT type="radio" name="gender" value="Male"> Male
   <INPUT type="radio" name="gender" value="Female"> Female</td><td width="200px"> <i style="color:red;" id="pointgendr"></i></td>
 </tr>
 <tr>
  <td><LABEL for="dob">Date of Birth:<sup style="color:#F00">*</sup> </LABEL></td>
  <td> 
  <select id="dd">
        <option value="dd">DD</option>
        <script type="text/javascript">
   for(var i=1;i<32;i++)
    document.write("<option value='"+i+"'>" + i+"</option> ");
   </script>
        </select>
                </select>
                 <select id="mmm">
         <option value="mmm">MMM</option>
         <option value="0">JAN</option>
         <option value="1">FEB</option>
         <option value="2">MAR </option>
         <option value="3">APR</option>
         <option value="4">MAY</option>
         <option value="5">JUN</option>
         <option value="6">JUL</option>
         <option value="7">AUG</option>
         <option value="8">SEP</option>
         <option value="9">OCT</option>
         <option value="10">Nov</option>
         <option value="11">DEC</option>
        </select>
        <select id="yyyy">
           <option value="yyyy"selected>YYYY</option>
        <script type="text/javascript">
   var dt= new Date();
   for(var i=1979;i<=dt.getFullYear()-18;i++)
    document.write("<option value='"+i+"'>" + i+"</option> ");
  </script>
  </select>
   </td><td width="200px"><i style="color:red;" id="pointdob"></i>
  </td>
 </tr>
 <tr>
  <td><LABEL for="address" style="text-align:left;">Address:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><textarea id="address"  name="address" rows="4" cols="20"></textarea></td><td width="200px"><i style="color:red;" id="pointadrs"></i>   
  </td>
  

 </tr>
 <tr>
  <td><LABEL for="contctno">Contact Number:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><INPUT type="text" id="contctno"></td><td width="200px"><i style="color:red;" id="pointcontct"></i></td>
 </tr>
 <tr>
  <td><LABEL for="email">Email:<sup style="color:red;">*</sup> </LABEL></td>
  <td><INPUT type="text" id="email"></td><td width="200px"><i style="color:red;" id="pointemail"></i></td>
 </tr>
 <tr>
  <td></td><td><br/><INPUT type="submit" onClick="return validateForm()" value="Submit">
  <INPUT type="reset" onClick="return confirmreset()"></td>
 </tr>
 
 <tr>
  <td></td><td style="font-size:12px;text-align:right;"><br/><i style="color:red;font-size:12px;align:right;" >* - Mandatory</i></td>
 </tr>
    </table>
<fieldset>
 </FORM></center>
 </div>
</div>


</body>
</html>

JAVASCRIPT CODE: innerHTMLValidation.js

 var namepattern=/^[a-zA-Z]+$/
 var phonepattern = /^\d{10}$/
 var emailpattern =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
 var emailpattern2 =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*$/
 var idpattern=/^\d{6}$/;

function validateForm()
{
 
 var x=document.forms["form1"]["firstname"];
 if (x.value=="")
   {
  
  document.getElementById('pointfn').innerHTML="Please enter the first name.";
    x.focus();
  return false;
   }
 
 else if(x.value.length>20)
   {
  x.value="";
  document.getElementById('pointfn').innerHTML="Please enter less than 20 characters.";
  x.focus();
  return false;
   }
 else if ((!namepattern.test(x.value)))
   {
  document.getElementById('pointfn').innerHTML="Please enter only alphabets.";
    x.value="";
  x.focus();
  return false;
   }

 document.getElementById('pointfn').innerHTML='';

 x=document.forms["form1"]["lastname"];

 if(x.value=="")
   {
  document.getElementById('pointln').innerHTML="Please enter the Last name.";
  x.focus();
  return false;
 } 
  else if(x.value.length>20)
   {
  x.value="";
  document.getElementById('pointln').innerHTML="Please enter less than 20 characters.";
  x.focus();
  return false;
 }
 else if (!namepattern.test(x.value))
   {
  x.value="";
  document.getElementById('pointln').innerHTML="Please enter only alphabets.";
  x.focus();
  return false;
 }
 document.getElementById('pointln').innerHTML="";
 if((document.form1.gender[0].checked==false)&&(document.form1.gender[1].checked==false))
 {
  document.form1.gender[0].focus();
  document.getElementById('pointgendr').innerHTML='Please select a gender.';
  return false;
 }
 document.getElementById('pointgendr').innerHTML='';
 var dd=document.form1.dd.value;
 var mmm=document.form1.mmm.value;
 var yyyy=document.form1.yyyy.value;
 if(!validdate(dd,mmm,yyyy))
 {
  document.getElementById('pointdob').innerHTML="Plaese select a valid date.";
  return false;
 }
  
 document.getElementById('pointdob').innerHTML="";
 x= document.getElementById("address");
 if(x.value==null || x.value=="" )
 {
  x.value="";
  document.getElementById('pointadrs').innerHTML="Please enter the address.";
  x.focus();
  return false;
 }
 else if(x.value.length<20)
   {
  x.value="";
  document.getElementById('pointadrs').innerHTML="Please enter atleast 20 characters.";
  x.focus();
  return false;
 }
 document.getElementById('pointadrs').innerHTML="";

 x=document.form1.contctno;

 if(x.value=="")
 {
  
  x.value="";
  document.getElementById('pointcontct').innerHTML="Please enter the contact number.";
  x.focus();
  return false;
 }
 else if(isNaN(x.value))
 {
  x.value="";
  document.getElementById('pointcontct').innerHTML="Please enter only digits.";
  x.focus();
  return false;
 }
 else if(x.value.length!=10)
 {
  x.value="";
  document.getElementById('pointcontct').innerHTML="Please enter only 10 digits.(Mobile number)";
  x.focus();
  return false;
 }
 else if(!phonepattern.test(x.value))
 {
  x.value="";
  document.getElementById('pointcontct').innerHTML="Please enter a valid contact number.";
  x.focus();
  return false;
 }
 document.getElementById('pointcontct').innerHTML="";

 x=document.form1.email;
 if(x.value=="")
 {
  x.value="";
  document.getElementById('pointemail').innerHTML="Please enter the email id.";
  x.focus();
  return false;
 }
 else if(!emailpattern.test(x.value))
 {
  x.value="";
  document.getElementById('pointemail').innerHTML="Please enter a valid email address.";
  x.focus();
  return false;
 }
 document.getElementById('pointemail').innerHTML="";
 return confirm("Do you want to submit the form?");
}
        function validdate(dd,mm,yyyy)
 {
  var dateobj = new Date(yyyy, mm, dd);
  var datecurrent= new Date();
  if((dateobj.getMonth()!=mm)||(dateobj.getDate()!=dd)||(dateobj.getFullYear()!=yyyy)||(dateobj>datecurrent))
  {
   return false;
  }
  return true;
 }
 
 function confirmreset()
 {
  if(confirm("Do you want to reset the form?"))
{
 document.getElementById('pointfn').innerHTML="";
 document.getElementById('pointln').innerHTML="";
 document.getElementById('pointgendr').innerHTML="";
 document.getElementById('pointdob').innerHTML="";
 document.getElementById('pointadrs').innerHTML="";
 document.getElementById('pointcontct').innerHTML="";
 document.getElementById('pointemail').innerHTML="";
 return true;
}
else
 return false;
 }

Registration Form Validation Example - HTML JAVASCRIPT ALERT BOX


Demo Registration Form

Male Female


* - Mandatory


HTML code: Demo Registration.html
<html >
<head>

       <!--external javascript-->
<script typ="text/javascript" src="validation.js" >
</script>

</head>
<body>

<center>
<h1>Demo Registration Form</h1>
<form name="form1"  method="post" action="success.html">
 
<table border='0'>
 <tr>
  <td><LABEL for="firstname">First Name:<sup style="color:#F00">*</sup> </LABEL></td>
         <td><INPUT type="text" id="firstname"></td>
 </tr>
 <tr>
  <td><LABEL for="lastname">Last Name:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><INPUT type="text" id="lastname"></td>
 </tr>
     
 <tr>
   <td><LABEL for="gender">Gender:<sup style="color:#F00">*</sup> </LABEL></td> <td><INPUT type="radio" name="gender" value="Male"> Male
   <INPUT type="radio" name="gender" value="Female"> Female </td>
 </tr>
 <tr>
  <td><LABEL for="dob">Date of Birth:<sup style="color:#F00">*</sup> </LABEL></td>
  <td> 
  <select id="dd">
        <option value="dd">DD</option>
        <script type="text/javascript">
   for(var i=1;i<32;i++)
    document.write("<option value='"+i+"'>" + i+"</option> ");
   </script>
        </select>
                </select>
                 <select id="mmm">
         <option value="mmm">MMM</option>
         <option value="0">JAN</option>
         <option value="1">FEB</option>
         <option value="2">MAR </option>
         <option value="3">APR</option>
         <option value="4">MAY</option>
         <option value="5">JUN</option>
         <option value="6">JUL</option>
         <option value="7">AUG</option>
         <option value="8">SEP</option>
         <option value="9">OCT</option>
         <option value="10">NOV</option>
         <option value="11">DEC</option>
        </select>
        <select id="yyyy">
           <option value="yyyy"selected>YYYY</option>
        <script type="text/javascript">
   var dt= new Date();
   for(var i=1979;i<=dt.getFullYear();i++)
    document.write("<option value='"+i+"'>" + i+"</option> ");
  </script>
  </select>
   
  </td>
 </tr>
 <tr>
  <td><LABEL for="address" style="text-align:left;">Address:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><textarea id="address"  name="address" rows="4" cols="20"></textarea>   
  </td>
  

 </tr>
 <tr>
  <td><LABEL for="contctno">Contact Number:<sup style="color:#F00">*</sup> </LABEL></td>
  <td><INPUT type="text" id="contctno"></td>
 </tr>
 <tr>
  <td><LABEL for="email">Email:<sup style="color:red;">*</sup> </LABEL></td>
  <td><INPUT type="text" id="email"></td>
 </tr>
 <tr>
  <td></td><td><br/><INPUT type="submit" onClick="return validateForm()" value="Submit">
  <INPUT type="reset" onClick="return confirmreset()"></td>
 </tr>
 
 <tr>
  <td></td><td style="font-size:12px;text-align:right;"><br/><i style="color:red;font-size:12px;align:right;" >* - Mandatory</i></td>
 </tr>
    </table>
 </FORM></center>



</body>
</html>


Javascript code: validation.js
function validateForm()
{
 
 var x=document.forms["form1"]["firstname"];
 if (x.value=="")
   {
  alert("Please enter the First name.");
  x.focus();
  return false;
   }
 
 else if(x.value.length>20)
   {
   alert("First name cannot be greater than 20 characters.");
  x.value="";
  x.focus();
  return false;
   }
 else if ((!namepattern.test(x.value)))
   {
  alert("First name should contain only alphabets.");
  x.value="";
  x.focus();
  return false;
   }

 x=document.forms["form1"]["lastname"];
 if(x.value=="")
   {
  alert("Please enter the Last name.");
  x.focus();
  return false;
 } 
  else if(x.value.length>20)
   {
  alert("Last name cannot be greater than 20 characters.");
  x.value="";
  x.focus();
  return false;
 }
 else if (!namepattern.test(x.value))
   {
    alert("Last name should contain only alphabets.");
  x.value="";
  x.focus();
  return false;
 }

 if((document.form1.gender[0].checked==false)&&(document.form1.gender[1].checked==false))
 {
  document.form1.gender[0].focus();
  alert("Please select a gender.");
  return false;
 }
 var dd=document.form1.dd.value;
 var mmm=document.form1.mmm.value;
 var yyyy=document.form1.yyyy.value;
 if(!validdate(dd,mmm,yyyy))
 {
  return false;
 }
  
 x= document.getElementById("address");
 if(x.value==null || x.value=="" )
 {
  alert("Please enter the Address.");
  x.value="";
  x.focus();
  return false;
 }
 else if(x.value.length<20)
   {
  alert("Address should be greater than 20 characters.");
  x.value="";
  x.focus();
  return false;
 }

 x=document.form1.contctno;
 if(x.value=="")
 {
  alert("Please enter the Contact number.");
  x.value="";
  x.focus();
  return false;
 }
 else if(isNaN(x.value))
 {
  alert("Contact number should contain only digits.");
  x.value="";
  x.focus();
  return false;
 }
 else if(x.value.length!=10)
 {
  alert("Contact number should contain only 10 digits.(Mobile number)");
  x.value="";
  x.focus();
  return false;
 }
 else if(!phonepattern.test(x.value))
 {
  alert("Invalid Contact number.");
  x.value="";
  x.focus();
  return false;
 }

 x=document.form1.email;
 if(!emailpattern.test(x.value))
 {
  alert("Invalid email id.");
  x.value="";
  x.focus();
  return false;
 }

 if(confirm("Do you want to submit the form?"))
{
alert("Registration Form Submitted Successfully.");
}
else
return false;

}
function validdate(dd,mm,yyyy)
 {
  var dateobj = new Date(yyyy, mm, dd);
  var datecurrent= new Date();
  if((dateobj.getMonth()!=mm)||(dateobj.getDate()!=dd)||(dateobj.getFullYear()!=yyyy)||(dateobj>datecurrent))
  {
   alert("Please select a valid date.");
   return false;
  }
  return true;
 }
 
 function confirmreset()
 {
  return confirm("Do you want to reset the form?");
 }

Related Posts Plugin for WordPress, Blogger...