Thursday, January 27, 2011

php example

UserValidation

<?php


class UserValidation{


function validatefirstName($firstName){

$namePattern="/^[a-zA-Z][a-zA-Z]*$/";
     
if(strlen($firstName)==0){

return "First Name Should Contains Characters";

}
else if(preg_match($namePattern,$firstName)!=true){

return "First name can contain only characters";

}
else{
//valid firstName
return "";
}

}//validatefirstName




function validateFullName($fullName){

$fullNamePattern="/^[a-zA-Z][a-zA-Z\\s]*$/";
     
if(strlen($fullName)<5){

return "Full Name Should At least 5 charcters long";
}
else if(preg_match($fullNamePattern,$fullName)!=true){

return "Full name can contain only characters";
}
else{
//valid fullname
return "";
}

}//validateFullName




function validateAddress($address){

if(strlen($address)==0){

return "address is required";
}
else{

return "";
}

}//validateAddress




function validateEmail($email){

$emailPattern="/^[a-zA-Z][a-zA-Z0-9_.]*[@][a-zA-Z0-9][a-zA-Z0-9]*[.][a-zA-Z][a-zA-Z]*$/";
     
if(preg_match($emailPattern,$email)!=true){

return "Invalid Email address";

}
else{
//valid email
return "";
}

}//validateEmail




function validateAge($age){

$agePattern="/^[0-9]*$/";
     
if(preg_match($agePattern,$age)!=true){

return "Invalid Age";

}
else{
//valid age
return "";
}

}//validAge


function validateUsername($username){

$usernamePattern="/^[a-zA-Z][a-zA-Z0-9]*$/";
if(strlen($username)==0){

return "username is required";
}
else if(strlen($username)<10){

return "username should contain at least 10 characters";
}  
else if(strlen($username)>15){

return "username can contain only maximum 15 characters";

}   
else if(preg_match($usernamePattern,$username)!=true){

return "Invalid Username";

}
else{
//valid age
return "";
}

}//validateusername





function validatePasswordAndPasswordConfirmation($password,$passwordConfirmation){

if($passwordConfirmation==""){

return "white spaces are not allowed for the password";

}
else if($password!=$passwordConfirmation){

return "Password does not match with the password confirmation";

}
else{
return "";
}

}//validatePassword




}//class



?>

registerNewUserController
<?php
include "../model/validation/UserValidation.php";
//registerNewUserController


if(isset($_POST["isAjax"])){

//creating validation object
$userValidation=new UserValidation;

if(isset($_POST["username"])){

//echo "validate username";

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}
}


if(isset($_POST["firstName"])){

//echo "validate firstName"; 

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}//firstName



if(isset($_POST["fullName"])){

//echo "validate fullName"; 

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}//fullName



if(isset($_POST["address"])){

//echo "validate address"; 


$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}



}


if(isset($_POST["email"])){

//echo "validate email"; 

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}


if(isset($_POST["age"])){

//echo "validate age"; 

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}

}


}//if outer
else if(isset($_POST["submit"])){

echo "Form submit request";


}
else{

echo "invalid request";

}

?>

validateRegistrationFormUsingAjax

<?php
include "../model/validation/UserValidation.php";
//ajax validation controller


if(isset($_POST["isAjax"])){

$userValidation=new UserValidation;


if(isset($_POST["username"])){

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}


if(isset($_POST["firstName"])){

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}//firstName



if(isset($_POST["fullName"])){

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}//fullName



if(isset($_POST["address"])){

$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}


if(isset($_POST["email"])){

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;

}
}


if(isset($_POST["age"])){

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}

}//if outer



//ajax request is to validate all data before submiting the form
if(isset($_POST["isAllData"])){

$userValidation=new UserValidation;
//$userValidationError="<b> The following Error Appear in Your Form </b><br/>";
$userValidationError="";

if(isset($_POST["username"])){

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";

}
}


if(isset($_POST["firstName"])){

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}//firstName



if(isset($_POST["fullName"])){

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}//fullName



if(isset($_POST["address"])){

$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}


if(isset($_POST["email"])){

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}

if(isset($_POST["age"])){

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}






if(strlen($userValidationError)!=0){

//there are validation errors
echo $userValidationError;


}
else{

//there no validation errors

echo "valid";

}

}


?>


view

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">


function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateFormItem(elementID,elementValue,spanTagId){

if (elementValue.length==0)
  {
  document.getElementById(spanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
 document.getElementById("txtAllErrors").innerHTML="";
    document.getElementById(spanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"../controller/validateRegistrationFormController.php",elementID,elementValue);

}


//password validation
function passwordValidation(passwordConf){
 
var password=(document.getElementById("password")).value;
 
 
 
if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }
 
xmlhttp=createXmlHttpObject();
 
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
 document.getElementById("txtPasswordConf").innerHTML="";
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }
 
var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","../controller/validateRegistrationFormController.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
 
 
}

</script>
</head>

<body>

<h2>User Registration form </h2>

<form method="POST" action="../controller/registerNewUserController.php" id="userRegistrationForm" name="userRegistrationForm">

UserName <input type="text" name="username" id="username" onChange="validateFormItem('username',this.value,'txtUsername')"/><p><span id="txtUsername"></span></p>

FirstName <input type="text" name="firstName" id="firstName" onChange="validateFormItem('firstName',this.value,'txtFirstName')"/><p><span id="txtFirstName"></span></p>

fullName <input type="text" name="fullName" id="fullName" onChange="validateFormItem('fullName',this.value,'txtFullName')"/><p><span id="txtFullName"></span></p>

Age <input type="text" name="age" id="age" onChange="validateFormItem('age',this.value,'txtAge')"/><p><span id="txtAge"></span></p>

Address <input type="text" name="address" id="address" onChange="validateFormItem('address',this.value,'txtAddress')"/><p><span id="txtAddress"></span></p>

Email <input type="text" name="email" id="email" onChange="validateFormItem('email',this.value,'txtEmail')"/><p><span id="txtEmail"></span></p>

password <input type="password" name="password" id="password" /><p><span id="txtPassword"></span></p>

password confirmation  <input type="password" name="passwordConf" id="passwordConf" onChange="passwordValidation(this.value)"/><p><span id="txtPasswordConf"> </span></p>

<input id="submit" type="submit" name="submit" value="Register" />

</form>


</body>
</html>

Monday, January 24, 2011

Ajax as a POST and GET http requests

the most commonly used two HTTP methods known as GET and POST can be used with Ajax. today i am going to show you how to use both GET and POST methods for retrieving/modifying  the data from the server side.  the most of the time, GET method is used to retrieve data from the server and POST method is used to modify or alter the data in the server. therefore it is good to know how to use both of these methods with Ajax for implementing your solution in most optimal and standard way. the below code can be placed inside the head tag of your webpage to make Ajax POST method request for the server side. In server side, the relevant Controller logic should be implemented to handle POST requests.

POST
<script type="text/javascript">
//this function is used to create the xmlHttp Object based on the bowser type
function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  

//this function is used to make the httpajax request to the server side
function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){
/* if you need you can send mutiple parameters. here i am sending only a single parameter for the server side.
   isAjax=true is a parameter which has been set by myself to provide support for the server side implemetation done by myself.
   it is not required to send this parameter ot make the ajax functionality works */
var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
//finally we are sending the parameters to the server side as a POST request
xmlhttp.send(parameters);

}

/* this is the actual usage. both above methods have been used here 
this is practical usage :- <input type='text" id="firstName" name="firstName" onchange="validateForm('firstName',this.value,'txtFirstName')/> <p><span id="txtFirstName"> </span></p>
*/
function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }
// we have called above createXmlHttpObject method to create the xmlHttp Object
xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }
/* we have called above sendAjaxHttpRequest method to make the actual ajax called for the server side. the url should be changed as your wish.
  i have implemeted this method to send only a single parameter for the server side. if you need you can send multiple parametes. in such case,
  you are required to provide parameters as below. 
   param1=param1value&param2=param3Value&....etc
   */
sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername


the following code segment can be used in your webpage for making Ajax GET request for the server side controller. in such case, the server side controller logic should be implemented in a way to deal with HTTP GET requests.

GET

<script type="text/javascript">
 
function validateUsername(userNameRetrived)
{ 
if (userNameRetrived.length==0)
  {
  document.getElementById("txtHint").innerHTML=""; 
  return;
  }
 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
 
else 
  {// code for IE6, IE5 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
  }
 
xmlhttp.onreadystatechange=function() 
  { 
  if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtUserNameMessage").innerHTML=xmlhttp.responseText; 
    }
  }
 
xmlhttp.open("GET","validate_form_data.php?username="+userNameRetrived,true); 
xmlhttp.send();
}
</script>

Hope this will be useful for you :)

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

Saturday, January 15, 2011

Codeigniter full MVC User Registration example

1. create the following view vie files in the application/views directory of the codeigniter framework.


(1). index.php 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page</title>
</head>

<body>
<?php
$this->load->helper('url');
$this->load->model("UserService");

$userService=new UserService();

$userIDs=$userService->getAllRegisteredUsersIDs();

?>
<table>
<tr><td>username</td><td>Edit</td><td>Remove</td></tr>
<?php for($index=0;$index<sizeof($userIDs);$index++){ ?>
<tr>
<td>Username</td><td><a href="<?php echo base_url(); ?>userAdministration/editUserDetails/<?php echo $userIDs[$index]; ?>">Edit User </a></td>
<td><a href="<?php echo base_url(); ?>userAdministration/removeRegisteredUser/<?php echo $userIDs[$index]; ?>">Remove User </a></td>
</tr>
<?php
}
?>

<tr><td><a href="<?php echo base_url(); ?>userAdministration/register">Add New User </a></td></tr>
</table>
</body>
</html> 

2. userRegisterView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');


$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/register',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label>
    </td>
    <td><input type="text"  id="username" name="username" value="<?php echo set_value('username'); ?>" onchange="validateForm('username',this.value,'txtUsername')" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" id="firstName" name="firstName" value="<?php echo set_value('firstName'); ?>" onchange="validateForm('firstName',this.value,'txtFirstName')"/>
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text"  id="lastName" name="lastName" value="<?php echo set_value('lastName'); ?>" onchange="validateForm('lastName',this.value,'txtLastName')"/>
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Password </label></td>
    <td><input id="password" type="password" name="password" value="<?php echo set_value('password'); ?>" />
    </td>
    <td><p><span id="txtPassword"><?php echo form_error('password'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" id="passwordConfirmation" name="passwordConfirmation" value="<?php echo set_value('passwordConfirmation'); ?>" onchange="passwordValidation(this.value)"/>
    </td>
    <td><p><span id="txtPasswordConf"><?php echo form_error('passwordConfirmation'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php echo set_value('age'); ?>" onchange="validateForm('age',this.value,'txtAge')"/>
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php echo set_value('address'); ?>" onchange="validateForm('address',this.value,'txtAddress')"/>
    </td>
    <td><p><span id="txtAddress"><?php echo form_error('address'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php echo set_value('email'); ?>" onchange="validateForm('email',this.value,'txtEmail')"/>
    </td>
    <td><p><span id="txtEmail"><?php echo form_error('email'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php echo set_value('telephone'); ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"><?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

3. userEditView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');

$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/editUser',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label></td>
    <td><input type="text" name="username" value="<?php if(isset($username)){ echo $username; }else{ echo set_value('username'); } ?>" onchange="validateForm('username',this.value,'txtUsername')" />
      <input type="hidden" value="<?php echo $userID; ?>" name="userID" id="userID" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" name="firstName" value="<?php if(isset($firstName)){ echo $firstName; }else{ echo set_value('firstName'); } ?>" onchange="validateForm('firstName',this.value,'txtFirstName')" />
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text" name="lastName" value="<?php if(isset($lastName)){ echo $lastName; }else{ echo set_value('lastName'); } ?>" onchange="validateForm('lastName',this.value,'txtLastName')"  />
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Password </label></td>
    <td><input type="password" name="password" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('password'); } ?>"/>
    </td>
    <td><?php echo form_error('password'); ?> </td>
  </tr>
  
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" name="passwordConfirmation" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('passwordConfirmation'); } ?>" onchange="passwordValidation(this.value)" />
    </td>
    <td><p><span id="txtPasswordConf"> <?php echo form_error('passwordConfirmation'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php if(isset($age)){ echo $age; }else{ echo set_value('age'); } ?>" onchange="validateForm('age',this.value,'txtAge')" />
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php if(isset($address)){ echo $address; }else{ echo set_value('address'); } ?>" onchange="validateForm('address',this.value,'txtAddress')" />
    </td>
    <td><p><span id="txtAddress"> <?php echo form_error('address'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php if(isset($email)){ echo $email; }else{ echo set_value('email'); } ?>" onchange="validateForm('email',this.value,'txtEmail')" />
    </td>
    <td><p><span id="txtEmail"> <?php echo form_error('email'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php if(isset($telephone)){ echo $telephone; }else{ echo set_value('telephone'); } ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"> <?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
  
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

2. Models

(1) UserModel.php
<?php
class UserModel extends CI_Model {

     var $userID='';
     var $username = '';
     var $password = '';
     var $email = '';
     var $firstName = '';
     var $address = '';
     var $age = '';
     var $telephone = '';
    

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    
    function setUserID($userIDprovided){
    
        $this->userID=$userIDprovided;
    }
    
    function getUserID(){
    
    return $this->userID;
    }
    
    function getUserName(){
    
    return $this->username;
    }
    
    function setUserName($usernameProvided){
    
    $this->username=$usernameProvided;
    
    }
    
    
    function getFirstName(){
    
    return $this->firstName;
    }
    
    function setFirstName($fisrtNameProvided){
    
    $this->firstName=$fisrtNameProvided;
    
    }
    
    
    function getLastName(){
    
    return $this->lastName;
    }
            
    function setLastName($lastNameProvided){
    
     $this->lastName=$lastNameProvided;
    
    }
    
    
    function getEmail(){
    
    return $this->email;
    }
    
    function setEmail($emailProvided){
    
    $this->email=$emailProvided;
    
    }    
    
    
    function getAge(){
    
    return $this->age;
    }
    
    function setAge($ageProvided){
    
    $this->age=$ageProvided;
    
    }
    
    
    function getTelephone(){
    
    return $this->telephone;
    }
    
    function setTelephone($telephoneProvided){
    
    $this->telephone=$telephoneProvided;
    
    }
    
    
    function getAddress(){
    
    return $this->address;
    }
    
    function setAddress($addressProvided){
    
    $this->address=$addressProvided;
    
    }
    

    function getPassword(){
    
    return $this->password;
    }
    
    function setPassword($passwordProvided){
    
    $this->password=$passwordProvided;
    
    }
    
    
        
}//class
        
?>    
  

(2.) EmailClass.php
<?php
class EmailClass extends CI_Model {

     var $emailUsername="xxxxxxxt@gmail.com";
     var $emailPassword="yourPassword";
     var $emailHost="ssl://smtp.googlemail.com";
     var $emailProtocol="smtp";
     var $emailPort="465";
     var $emaiType="html";
    
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        //$this->load->helper("url");
    }
    
    
function sendEmail($emailFrom,$emailTo,$subject,$message){
    
 $config = Array(
  'protocol' => $this->emailProtocol,
  'smtp_host' => $this->emailHost,
  'smtp_port' => $this->emailPort,
  'smtp_user' => $this->emailUsername, // change it to yours
  'smtp_pass' => $this->emailPassword, // change it to yours
  'mailtype' => $this->emaiType,
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);
  $this->load->library('email', $config);
  $this->email->set_newline("\r\n");
  $this->email->from($emailFrom); // change it to yours
  $this->email->to($emailTo); // change it to yours
  $this->email->subject($subject);
  $this->email->message($message);

  if($this->email->send())
  {

   return true;

  }
  else
  {
   show_error($this->email->print_debugger());
   
   return false;
  }
  
    
}
    
        
}//class
        
?>    


(3.)UserService.php
<?php
class UserService extends CI_Model {


   function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        $this->load->database();    

    }
    
    
     function createNewUser($user){
        
            
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

      
       $insertStatus=$this->db->insert('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address      ,'telephone'=>$telephone)); 
       
       if($insertStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    }//createNewUser
    
    
    
    
    function editUserDetails($user){
    
    
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

        $this->db->where('userID', $user->getUserID());
       $updatedStatus=$this->db->update('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address,'telephone'=>$telephone)); 
       
       if($updatedStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    
    
    
    }//editUserDetails
    
    
    
    
    function getAllRegisteredUsersIDs(){
        
    $this->db->select('userID');
    $query = $this->db->get('user');
    $selectedDataArray=array();
    
    $i=0;
    
    foreach ($query->result() as $row){
    
    $selectedDataArray[$i]=$row->userID;
    $i++;
    }
    
     return $selectedDataArray;
    
    }//getAllRegisteredUsersIDs
    
    
    
    
    
    function removeRegisteredUser($user){
        
    $this->db->where('userID', $user->getUserID());
    $this->db->delete('user'); 
    
    }//removeRegisteredUser
    
    
    
    
    function getSelectedUserDetails($user){
        
        $query = $this->db->get_where('user', array('userID' => $user->getUserID()));
    
        $selectedData="";
        
        foreach ($query->result() as $row){

         $selectedData=array("username"=>$row->username,"firstName"=>$row->firstName,"lastName"=>$row->lastName,"password"=>$row->password,"age"=>$row->age,"telephone"=>$row->telephone,"address"=>$row->address,"email"=>$row->email,"userID"=>$row->userID);
        
        }
        
        return $selectedData;
        
    }//getSelectedUserDetails
    
    
    
    function isUserNamealreadyRegisterd($user){
        
    $username=$user->getUserName();
    
    $query = $this->db->get_where('user', array('username' => $username));
    
    if($query->num_rows()==0){
    
    return false;
    
    }
    else{
    
    return  true;
    }
      
    }//function
    
    
   }//class
    
    
    
?>
 
3.  Controller

UserAdministration.php
<?php

class userAdministration extends CI_Controller {


    public function index()
    {
        echo 'welcome to userAdministration Controller';
    }
    
    
    public function register(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->model("EmailClass");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
                                                
            $dbInserted=$userService->createNewUser($userModel);

            
            if($dbInserted){
            
                //echo "registration email should be sent";
        
              $emailClass=new EmailClass();
            
              $emailSentStatus=$emailClass->sendEmail("chathuranga.t@gmail.com","chathuranga.t@gmail.com","new user registration","chathurangat.blogspot.com");
            
             if($emailSentStatus){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
            }//if
                                    
        }//else            
    }//register    
    
    
    function removeRegisteredUser($userID){
    
    
    //echo "request for remeving user with  userID ".$userID;
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $userService->removeRegisteredUser($userModel);
            
            redirect(base_url()); //with error message
            
         
    }//removeRegisteredUser
    
    
    
    function editUserDetails($userID){
    
    //echo "request for editing user with userID ".$userID;
    
             $this->load->helper(array('form', 'url'));
             $this->load->library('form_validation');        
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $retievedUserData=$userService->getSelectedUserDetails($userModel);
            
            $this->load->view("userEditView",$retievedUserData);
            
    
    }//display Edit user details from
    
    
    
    
    public function editUser(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
            $userModel->setUserID($this->input->post('userID', TRUE));    
                                            
            $dbCommited=$userService->editUserDetails($userModel);
            
            
            if($dbCommited){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
                                    
        }//else            
    }//editUser    
    
    
    
    function ajaxValidation(){
    
    $this->load->model("UserModel");
    $this->load->model("UserService");

      $userModel=new UserModel();    
      $userService=new UserService();
    //validating user input using ajax
    
     $this->load->helper(array('form', 'url'));
     $this->load->library('form_validation');
    
    $username=$this->input->post('username');
    $email=$this->input->post('email');
    $address=$this->input->post('address');
    $telephone=$this->input->post('telephone');
    $age=$this->input->post('age');
    $lastName=$this->input->post('lastName');
    $firstName=$this->input->post('firstName');
    $password=$this->input->post('password');    
    $passwordConf=$this->input->post('passwordConf');        
        
    //username validate                
    if(isset($username) && $username!=""){
    
    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    else{
    
    $userService=new UserService();
    $userModel=new UserModel();
    
    $userModel->setUserName($username);
    
    $userStatus=$userService->isUserNamealreadyRegisterd($userModel);
    
    if($userStatus){
    
    echo "Username is already taken";
    
    }
    else{
    
    echo "Username is avaialable";
    
    }
    }
    }//username
    
    
    
    //validating email
    
    if(isset($email) && $email!="" ){
    
     $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    
    }//email
    
    
      //validating address
    
        if(isset($address) && $address!="" ){
    
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
       }

       }//address
    
    
    
        
    
       //validating age
    
       if(isset($age) && $age!="" ){
    
         $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//age
    
    
        //validating telephone
    
        if(isset($telephone) && $telephone!="" ){
    
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//telephone
    
    
       //validating first name
    
        if(isset($firstName) && $firstName!="" ){
    
          $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
          echo validation_errors();
    
         }
                 
        }//firstName
    
    
    
        //validating last name
    
        if(isset($lastName) && $lastName!="" ){
    
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
         echo validation_errors();
    
         }
                 
        }//lastName
        
        
        
        
        if(isset($password) && $password!="" && isset($passwordConf) && $passwordConf!="" ){
        
    
        if($password!=$passwordConf){
        
        echo  "Password and Password Confirmation field does not match";
                
        }

        }//password
    
    
    
    }//ajaxValidation
    
}//class

?> 




Configuration in application/config/database.php
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'test_mvc';
$db['default']['dbdriver'] = 'mysql';


My SQL Table Structure
CREATE TABLE IF NOT EXISTS `user` (
  `userID` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `address` varchar(500) NOT NULL,
  `email` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `telephone` varchar(100) NOT NULL,
  PRIMARY KEY  (`userID`),
  UNIQUE KEY `username` (`username`)
) 





regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

Tuesday, December 7, 2010

Spring MVC Annotation based Helloworld Example with LOG4J logging support


Today we will look at how to write Spring MVC hello world application using Spring Annotations. This tutorial will be completely different from other available tutorials in the web because, I have tried to show how to externalize property values from the BeanFactory definition and how to place them in a separate standard files called properties files. In addition, I will be using apache log4j framework to make the required logs for this application. Therefore you will be having the chance to investigate more on these technologies throughout this article. The overall directory and the file structure of the project is as follows.


I have used the following technologies and frameworks to make this simple example.

Apache Maven as the building tool
Apache Log4J as the logging framework
Spring MVC framework
Apache Tomcat for running this Application
Intelli J IDEA as the Development IDE


you can see the content of the each file as below.

 
pom.xml 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringMVC</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>SpringMVC</name>

    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>

    </repositories>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <!-- spring dependency starts-->
        <!-- Spring Framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <!-- Spring MVC Framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!-- spring dependency ends-->

        <!-- JSTL Dependencies start -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!-- JSTL Dependencies ends -->


        <!--Logging Dependencies Starts-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--Logging Dependencies Ends-->

    </dependencies>


    <build>
        <plugins>

            <!-- Maven compiler plugin that says to use JDK 1.6 version for compiling the project -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>

                </configuration>

            </plugin>


            <!-- Maven WAR  plugin -->
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.0.2</version>

                <configuration>
                    <warSourceDirectory>src/main/webapps</warSourceDirectory>
                </configuration>

            </plugin>
        </plugins>
        <!-- Final project build name -->
        <finalName>SpringMVC</finalName>
    </build>

</project>


HelloWorldControlller.java

this is the main(core) controller of this simple web application. You can see that we have used annotations for request mappings and other required configurations. As you can see the developer.name and developer.email properties have been defined in a external property file and they are accessed in the controller using the special annotations dedicated for that. The property values will be injected to the relevant variables using the @Value annotation.


package org.convey.example.Controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
Author: Chathuranga Tennakoon
Email: chathuranga.t@gmail.com

 */

@Controller
@RequestMapping("/HelloWorld")
public class HelloWorldController {


    private static final Logger logger = Logger.getLogger(HelloWorldController.class);

    @Value("${developer.name}")
    private String developerName;

    @Value("${developer.email}")
    private String developerEmail;

    @RequestMapping("/hello")
    public ModelAndView helloWorldMethod(){

        logger.debug(" invoking the helloWorldMethod method ");

        ModelAndView model=new ModelAndView("SayHelloView");

        model.addObject("developer_name",developerName);
        model.addObject("developer_email",developerEmail);


        return model;

    }//helloWorldMethod

}//helloWorldController



messages.properties

this file is located inside the resources/properties/ directory. The content of this file is as follows.

#Sample Screen Message values
developer.name=chathuranga tennakoon
developer.email=chathuranga.t@gmail.com

 

 
web.xml

you will see that the Spring MVC Dispatcher servlet is mapped and configured inside the web.xml file.
In additon, the log4j configuration is also done inside the web.xml file.(furthermore you can define and configure Filters and Listeners inside the web.xml file if required.)

<?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>Spring3-HelloWorld-Example</display-name>
<!-- LOG4J Configuration -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/resources/log4j.xml</param-value>
</context-param>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring MVC Dispatcher Servlet Mapping start -->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring MVC Dispatcher Servlet Mapping ends -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>


hello-servlet.xml

this represents the Dispatcher servlet of your web application. As you can see in the web.xml , you have named the dispater servlet as hello. Therefore your dispatcher servlet will be named as hello-servlet.xml. The beans that are declared in this servlet will be initiated when the Dispatcher servlet loading time. All the declared beans will be created in the Spring bean container.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<import resource="applicationContext.xml"/>

<bean id="handlerMappingC" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop
key="/HelloWorld/*">
HelloController
</prop>

</props>
</property>
</bean>

<bean id="HelloController" class="org.convey.example.Controller.HelloWorldController"/>

</beans>

SayHelloView.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<body>
<h1>Spring MVC Hello World Annotation Example</h1>

<!-- JSTL Tag libraries are required for the EL(Expression Language) -->
<h5>developed by : ${developer_name}</h5>
<h5>Email : ${developer_email}</h5>

</body>
</html>



applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.convey.example.Controller" />
<!-- actual view is resolved with the prefix + resolverName + suffix . if the resolverName is sayHelloView, then the actual resolved view will be /WEB-INF/view/sayHelloView.jsp ( /WEB-INF/view/ + sayHelloView + .jsp ) -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- the below bean is configured to define external property file for defining property values for the application -->
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- messages have been defined inside the resources/properties/messages.properties file -->
<value>classpath:properties/messages.properties</value>
</list>
</property>
</bean>

</beans>


log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%x] %c{1} %m%n" />
</layout>
</appender>

<appender name="FileAppender" class="org.apache.log4j.FileAppender">
<!-- the log file will be available inside the logs directory of the tomcat installation. the name of the log file is sample.log -->
<param name="File" value="../logs/sample.log"/>
<!-- the log will contains the log messages started from the INFO level..(info or less) -->
<param name="Threshold" value="INFO"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%x] %c{1} %m%n" />
</layout>
</appender>

<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>

</log4j:configuration>


How to run the project?

After placing the all required files in the relevant locations, you can use maven building tool to build your application. The following command can be used in your terminal to build the web application.

mvn clean install

once the project is build, you will see the war file (SpringMVC.war) inside the directory called target in your project source location. You can deploy the SpringMVC.war file in the tomcat server and see the output. It will display as below.

Browse the following URL to see the output.

http://localhost:8080/SpringMVC/HelloWorld/hello




 
Please remember to check the logs directory of your tomcat server installation and see whether there is a file called sample.log. This file should contains the log records which were generated during the execution of this web application. In additon, check whether the console appenders. In order to check the console appenders, you can use the following command in your terminal.(i assume that you are using a linux operating system.)

tail -f logs/catalina.out



regards
Chathuranga Tennakoon