Search This Blog

Sunday 28 July 2013

Converting XML into java objects by using SAX Parser



Converting XML into java objects by using SAX Parser


src\AccountXmlHandler.java
==========================================

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Pedababu M
 *
 */
public class AccountXmlHandler extends DefaultHandler {

       private Account acct;
       private String temp;
       private ArrayList<Account> accList = new ArrayList<Account>();


       public static void main(String[] args) throws IOException, SAXException,
                     ParserConfigurationException {
              SAXParserFactory spfac = SAXParserFactory.newInstance();
              SAXParser sp = spfac.newSAXParser();
              AccountXmlHandler handler = new AccountXmlHandler();
              sp.parse("D:\\workspace\\XmlToBean\\src\\bank.xml", handler);
            
              handler.readList();

       }



       public void characters(char[] buffer, int start, int length) {
              temp = new String(buffer, start, length);
       }
     

       public void startElement(String uri, String localName,
                     String qName, Attributes attributes) throws SAXException {
           System.out.println("startElement --- uri" + uri);
           System.out.println("startElement --- qName::::" + qName);
           System.out.println("startElement --- localName" + localName);
           System.out.println("startElement --- attributes" + attributes.getLocalName(1));
              temp = "";
              if (qName.equalsIgnoreCase("Account")) {
                     acct = new Account();
                     acct.setType(attributes.getValue("type"));

              }
       }


       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     accList.add(acct);

              } else if (qName.equalsIgnoreCase("name")) {
                     acct.setName(temp);
              } else if (qName.equalsIgnoreCase("accountid")) {
                     acct.setAccountId(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("blanceamount")) {
                     acct.setBlanceAmount(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("ssn")) {
                     acct.setSsn(temp);
              }

       }

       private void readList() {
              System.out.println("No of  the accounts in bank '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
     
}

src\Account.java
================================

/**
 * @author Pedababu M
 *
 */
public class Account {
          private String name;
           private int accountId;
            private int blanceAmount;
           private String type;
           String ssn;

           public Account() {
           }

           public Account(String name, int accountId, int blanceAmount, String type) {
                  this.name = name;
                  this.blanceAmount = blanceAmount;
                  this.accountId = accountId;
                  this.type = type;
           }

           /**
             * @return the name
             */
            public String getName() {
                return name;
            }

            /**
             * @param name the name to set
             */
            public void setName(String name) {
                this.name = name;
            }

            /**
             * @return the accountId
             */
            public int getAccountId() {
                return accountId;
            }

            /**
             * @param accountId the accountId to set
             */
            public void setAccountId(int accountId) {
                this.accountId = accountId;
            }

            /**
             * @return the blanceAmount
             */
            public int getBlanceAmount() {
                return blanceAmount;
            }

            /**
             * @param blanceAmount the blanceAmount to set
             */
            public void setBlanceAmount(int blanceAmount) {
                this.blanceAmount = blanceAmount;
            }

            /**
             * @return the type
             */
            public String getType() {
                return type;
            }

            /**
             * @param type the type to set
             */
            public void setType(String type) {
                this.type = type;
            }

            /**
             * @return the ssn
             */
            public String getSsn() {
                return ssn;
            }

            /**
             * @param ssn the ssn to set
             */
            public void setSsn(String ssn) {
                this.ssn = ssn;
            }

           public String toString() {
                  StringBuffer sb = new StringBuffer();
                  sb.append("Account Details - ");
                  sb.append("Name:" + getName());
                  sb.append(", ");
                  sb.append("Account Type:" + getType());
                  sb.append(", ");
                  sb.append("Account Id:" + getAccountId());
                  sb.append(", ");
                  sb.append("Balance amount:" + getBlanceAmount());
                  sb.append(",");
                  sb.append("Ssn:" + getSsn());
                  sb.append(".");
                  return sb.toString();
           }
}

src\bank.xml
=================================

<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <accountid>1001</accountid>
            <name>MPB</name>
            <blanceamount>10000</blanceamount>
            <ssn>32323-32323</ssn>
      </Account>
      <Account type="current">
            <accountid>1001</accountid>
            <name>XYZ</name>
            <blanceamount>10000</blanceamount>
            <ssn>4343434-43434</ssn>
      </Account>
</Bank>

Wednesday 24 July 2013

Spring 2 MVC JdbcDaoSupport RowMapper Validator and Layers Demo



Spring 2 MVC JdbcDaoSupport RowMapper Validator and Layers Demo


Create web dynamic project in eclipse with "SpringJDBC"

WEB-INF\web.xml
==================


<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
   
   

 <display-name>Spring Example</display-name>

  <servlet>
    <servlet-name>basicspring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>basicspring</servlet-name>
    <url-pattern>*.obj</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>


WEB-INF\basicspring-servlet.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
   
    <bean id="basicspringController" class="com.web.spring.BasicSpringController" />
    <!--
        <bean name="/hello.obj"
        class="com.web.spring.BasicSpringController" />
    -->
    <bean id="userValidator" class="com.web.spring.UserValidator" />

    <bean id="userLoginFormController" class="com.web.spring.UserLoginFormController">
        <property name="iUserService"><ref bean="iUserService"/> </property>
        <property name="sessionForm">
            <value>true</value>
        </property>
        <property name="commandName">
            <value>user</value>
        </property>
        <property name="commandClass">
            <value>com.web.spring.User</value>
        </property>
        <property name="validator">
            <ref bean="userValidator" />
        </property>
        <property name="formView">
            <value>login</value>
        </property>
        <property name="successView">
            <value>accountdetails.obj</value>
        </property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>messages</value>
        </property>
    </bean>

    <!--
        <bean id="beanMapping"
        class="org.springframework.web.servlet.handler.BeanUrlHandlerMapping">
        <property name="order" value="1" /> </bean>
    -->

    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <!--<property name="order" value="2" />-->
        <property name="mappings">
            <props>
                <prop key="/hello.obj">basicspringController</prop>
                <prop key="/userlogin.obj">userLoginFormController</prop>
                <prop key="/accountdetails.obj">acountDetailsController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
   
    <bean id ="iUserService" class="com.web.spring.user.UserService">
        <property name="iUserDao"><ref bean="iUserJDBCDao"/> </property>
    </bean>
    <bean id ="iUserJDBCDao" class="com.web.spring.dao.UserJDBCDao">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
    </bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
    </bean>
   
    <bean id="acountDetailsController" class="com.web.spring.AcountDetailsController">
        <property name="iAccountDetails">
            <ref bean="iAccountDetails" />
        </property>
    </bean>
    <bean id ="iAccountDetails" class="com.web.spring.account.AccountDetails">
        <property name="iAccountDetailsDao"><ref bean="iAccountDetailsDao"/> </property>
    </bean>
    <bean id ="iAccountDetailsDao" class="com.web.spring.dao.AccountDetailsDao">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
    </bean>
</beans>


com\web\spring\UserValidator.java
================================


package com.web.spring;

import org.springframework.validation.*;

/**
 * @author Pedababu M
 *
 */
public class UserValidator implements Validator {

    public boolean supports(Class someclass) {
        return someclass.equals(User.class);
    }

    public void validate(Object obj, Errors errors) {
        User user = (User) obj;
        if(user.getUsername().length() < 3)
            errors.rejectValue("username","username.invalid","Please enter a valid username");
        if(user.getPassword().length() < 6)
            errors.rejectValue("password","password.invalid","Please enter a valid password");
    }
};

com\web\spring\UserLoginFormController.java
==========================================


package com.web.spring;

import javax.servlet.ServletException;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.web.spring.user.IUserService;

/**
 * @author Pedababu M
 *
 */
public class UserLoginFormController extends SimpleFormController {
private IUserService iUserService;
    /**
 * @return the iUserService
 */
public IUserService getiUserService() {
    return iUserService;
}
/**
 * @param iUserService the iUserService to set
 */
public void setiUserService(IUserService iUserService) {
    this.iUserService = iUserService;
}
    public ModelAndView onSubmit(Object command) throws ServletException {
        User user = (User) command;
        if(iUserService.isValidUser(user))
            return new ModelAndView(new RedirectView(getSuccessView()));
        else return new ModelAndView("error");
    }
}


com\web\spring\User.java
========================


package com.web.spring;

/**
 * @author Pedababu M
 *
 */
public class User {

    private String username, password;

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
};

com\web\spring\BasicSpringController.java
======================================


package com.web.spring;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
/**
 * @author Pedababu M
 *
 */
public class BasicSpringController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String now = new java.util.Date().toString();
        return new ModelAndView("hello","now",now);
    }
};

com\web\spring\AcountDetailsController.java
=========================================


package com.web.spring;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.web.spring.account.IAccountDetails;

/**
 * @author Pedababu M
 *
 */
public class AcountDetailsController implements Controller {

    private IAccountDetails iAccountDetails;
   
    /**
     * @return the iAccountDetails
     */
    public IAccountDetails getiAccountDetails() {
        System.out.println("AcountDetailsController-getiAccountDetails");
        return iAccountDetails;
    }

    /**
     * @param iAccountDetails the iAccountDetails to set
     */
    public void setiAccountDetails(IAccountDetails iAccountDetails) {
        this.iAccountDetails = iAccountDetails;
    }

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String now = new java.util.Date().toString();

        Map myModel = new HashMap();
        myModel.put("now",now);
        myModel.put("accounts",getiAccountDetails().showAccountDetails());
        return new ModelAndView("account","model",myModel);
    }

   
};

com\web\spring\user\UserService.java
====================================


package com.web.spring.user;

import com.web.spring.User;
import com.web.spring.dao.IUserDao;

/**
 * @author Pedababu M
 *
 */
public  class UserService implements IUserService{

    IUserDao iUserDao;
    /**
     * @return the iUserDao
     */
    public IUserDao getiUserDao() {
        return iUserDao;
    }
    /**
     * @param iUserDao the iUserDao to set
     */
    public void setiUserDao(IUserDao iUserDao) {
        this.iUserDao = iUserDao;
    }
    public boolean isValidUser(User user) {
        return iUserDao.isValidUser(user);
       
    }

}


com\web\spring\user\IUserService.java
=====================================

package com.web.spring.user;

import com.web.spring.User;

/**
 * @author Pedababu M
 *
 */
public interface IUserService {
    public boolean isValidUser(User user);
}


com\web\spring\dao\UserJDBCDao.java
=====================================

package com.web.spring.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.web.spring.User;

/**
 * @author Pedababu M
 *
 */
public class UserJDBCDao extends JdbcDaoSupport implements IUserDao {

    public boolean isValidUser(User user) {
        JdbcTemplate jt = getJdbcTemplate();
        int count = jt
                .queryForInt("select count(*) from User_800890 where user_name = '"
                        + user.getUsername()
                        + "' and user_password='"
                        + user.getPassword() + "'");
        System.out.println("count::::::::::" + count);
        if (count>0) return true;
        else return false;
    }
}


com\web\spring\dao\IUserDao.java
=================================

package com.web.spring.dao;

import com.web.spring.User;

/**
 * @author Pedababu M
 *
 */
public interface IUserDao{
    public boolean isValidUser(User user);
}


com\web\spring\dao\IAccountDetailsDao.java
=========================================

package com.web.spring.dao;

import java.util.List;

/**
 * @author Pedababu M
 *
 */
public interface IAccountDetailsDao {
    public List showAccountDetails();
}


com\web\spring\dao\AccountDetailsDao.java
============================================


package com.web.spring.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.web.spring.account.Account;



/**
 * @author Pedababu M
 *
 */
public class AccountDetailsDao extends JdbcDaoSupport implements IAccountDetailsDao{
    public List showAccountDetails() {
        System.out.println("AccountDetailsDao--showAccountDetails");
        JdbcTemplate jt = getJdbcTemplate();
        return jt.query ( "select * from account_800890"
                        , new AccountRowMapper()
                        );
    }
    class AccountRowMapper implements RowMapper {
          public Object mapRow(ResultSet rs, int index) throws SQLException {
            Account account = new Account();
            account.setAccountName(rs.getString(2));
            account.setAccountType(rs.getString(3));
            account.setAccountID(rs.getString(4));
            account.setAccountBlance(rs.getInt(5));
            System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + rs.getInt(4));
            return account;
          }     
        }//class EmployeeRowMapper
}


com\web\spring\account\IAccountDetails.java
=========================================

package com.web.spring.account;

import java.util.List;

/**
 * @author Pedababu M
 *
 */
public interface IAccountDetails {
    public List showAccountDetails();
}


com\web\spring\account\AccountDetails.java
=========================================

package com.web.spring.account;

import java.util.List;

import com.web.spring.dao.IAccountDetailsDao;

/**
 * @author Pedababu M
 *
 */
public class AccountDetails implements IAccountDetails{
    private IAccountDetailsDao iAccountDetailsDao;
    /**
     * @return the iAccountDetailsDao
     */
    public IAccountDetailsDao getiAccountDetailsDao() {
        System.out.println("AccountDetails-getiAccountDetailsDao");
        return iAccountDetailsDao;
    }
    /**
     * @param iAccountDetailsDao the iAccountDetailsDao to set
     */
    public void setiAccountDetailsDao(IAccountDetailsDao iAccountDetailsDao) {
        this.iAccountDetailsDao = iAccountDetailsDao;
    }
    public List showAccountDetails() {
        System.out.println("AccountDetails--showAccountDetails");
        return iAccountDetailsDao.showAccountDetails();
    }
}


com\web\spring\account\Account.java
===================================


package com.web.spring.account;

/**
 * @author Pedababu M
 *
 */
public class Account {
    private String accountName;
    private String accountType;
    /**
     * @return the accountName
     */
    public String getAccountName() {
        return accountName;
    }
    /**
     * @param accountName the accountName to set
     */
    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }
    /**
     * @return the accountType
     */
    public String getAccountType() {
        return accountType;
    }
    /**
     * @param accountType the accountType to set
     */
    public void setAccountType(String accountType) {
        this.accountType = accountType;
    }
    /**
     * @return the accountID
     */
    public String getAccountID() {
        return accountID;
    }
    /**
     * @param accountID the accountID to set
     */
    public void setAccountID(String accountID) {
        this.accountID = accountID;
    }
    /**
     * @return the accountBlance
     */
    public int getAccountBlance() {
        return accountBlance;
    }
    /**
     * @param accountBlance the accountBlance to set
     */
    public void setAccountBlance(int accountBlance) {
        this.accountBlance = accountBlance;
    }
    private String accountID;
    private int accountBlance;
}

account.jsp
==============================


<%@ include file="include.jsp"%>
<html>
<head>
<title>Account Details</title>
</head>
<body>
    <h3>Account Details</h3>
    <table>
        <tr>
            <th>Account Name</th>
            <th>Account Type</th>
            <th>Account ID</th>
            <th>Account Blance</th>
        </tr>
        <c:forEach items="${model.accounts}" var="account">
            <tr>
                <td><c:out value="${account.accountName}" /></td>
                <td><c:out value="${account.accountType}" /></td>
                <td><c:out value="${account.accountID}" /></td>
                <td><c:out value="${account.accountBlance}" /><td>
            </tr>
        </c:forEach>
    </table>
    Click Here to <a href="/SpringJDBC/userlogin.obj">Logout</a>
</body>
</html>

hello.jsp
=======================

<%@ include file="include.jsp" %>
<html>
<body>
<h1>Welcome to Spring!!</h1>
Click Here to <a href="/SpringJDBC/userlogin.obj">Login</a>
</body>
</html>

include.jsp
========================

<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/fmt.tld" prefix="fmt" %>

error.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>Insert title here</title>
</head>
<body>
Invalid user details
</body>
</html>

index.jsp
================================

<%@ include file="include.jsp" %>

<c:redirect url="hello.obj" />

login.jsp
=================================

<%@ include file="include.jsp" %>
<%@ taglib uri="/WEB-INF/spring.tld" prefix="spring" %>
<html>
<body>
<form method="post">

<br>Enter username:
<spring:bind path="user.username">
<input type="text" name="username" value="<c:out value="${status.value}"/>">
<i><c:out value="${status.errorMessage}"/></i>
</spring:bind>

<br>Enter password:
<spring:bind path="user.password">
<input type="text" name="password" value="<c:out value="${status.value}"/>">
<i><c:out value="${status.errorMessage}"/></i>
</spring:bind>
<br>
<input type="submit" value="Login">
</form>
</body>
</html>

sql script
===================================================================

create table user_800890(user_id int,user_name varchar, user_password varchar)
insert into user_800890 values (1,'testuser', 'testuser')

create table account_800890(account_id int,account_name varchar, account_type varchar, account_number varchar,
account_balance integer)
insert into account_800890 values (1,'Bob Checking', 'Checking', '111223333-C33',60000)
insert into account_800890 values (2,'Bob Savings', 'Savings', '111223333-C33',60000)
insert into account_800890 values (3,'Bob Current', 'Current', '111223333-C33',60000)

Tuesday 23 July 2013

Spring 3 Demo with annotation-driven




Spring 3 Demo with annotation-driven
Create web dynamic java project with "Spring3Demo"

WEB-INF\web.xml
=============================================================

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Hello Program</display-name>
    <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>*.htm</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/hello-servlet.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>     

WEB-INF\hello-servlet.xml
=============================================================

<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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />



    <context:component-scan base-package="com.xyz.controller" />


    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages" />
    </bean>

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>                               

com\xyz\controller\HelloController.java
=============================================================

package com.xyz.controller;

import java.util.Date;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xyz.bo.Customer;

@Controller
@RequestMapping("hello")
public class HelloController {

    @RequestMapping(value ="/welcome", method = RequestMethod.GET)
    public String welcome(Model model) {
        Date date = new Date();
        System.out.println("here in welcome");
        model.addAttribute("dateVisited", date);
        // takes the default return view as hello
        return "hello";
    }
    @RequestMapping(value = "/customerform", method = RequestMethod.GET)
    public String customerForm(Map model) {
        Date date = new Date();
        System.out.println("here in welcome");
        Customer customer = new Customer();
        model.put("customer", customer);
        // takes the default return view as hello
        return "custform";
    }
    @RequestMapping(value="/customerProcess", method = RequestMethod.POST)
    public String addCustomer(@Valid Customer customer, BindingResult result, Map model) {
        customer = (Customer) model.get("customer");
        if (result.hasErrors()) {
            System.out.println("hasErrors:::::::::::hasErrors");
            return "custform";
        } else {
            model.put("customer", customer);
            System.out.println("customersuccess:::::::::::customersuccess");
            return "customersuccess";
        }

    }
}

com\xyz\bo\Customer.java
=============================================================

package com.xyz.bo;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

public class Customer {
    @NotEmpty //make sure name is not empty
    @Size(max=16)
    String customerName;
    @NotEmpty
    String location;
    @Range(min = 1, max = 150) //age need between 1 and 150
    int customerCode;
    public String getCustomerName() {
        return customerName;
    }
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public int getCustomerCode() {
        return customerCode;
    }
    public void setCustomerCode(int customerCode) {
        this.customerCode = customerCode;
    }
}

index.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>Insert title here</title>
</head>
<body>
<h2>Welcome To Spring3</h2>
<BR/>
<a href="/Spring3Demo/hello/welcome.htm">Click welcome</a><br/>
<a href="/Spring3Demo/hello/customerform.htm">Customer form</a>
</body>
</html>

jsp\custform.jsp
=============================================================

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring"
    uri="http://www.springframework.org/tags/form"%>
<!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>Insert title here</title>
</head>
<body>
<BR/>
<a href="/Spring3Demo/hello/welcome.htm">Click welcome</a><br/><a href="/Spring3Demo/hello/customerform.htm">Customer form</a>
<BR/>
<spring:form action="customerProcess.htm" method="post" commandName="customer">
    <table>
        <tr>
            <td>Enter Customer Name :</td>
            <td><spring:input path="customerName" /><spring:errors
                path="customerName" /></td>
        </tr>
        <tr>
            <td>Enter Location :</td>
            <td><spring:input path="location" /><spring:errors
                path="location" /></td>
        </tr>
        <tr>
            <td>Enter Location :</td>
            <td><spring:input path="customerCode" /><spring:errors
                path="customerCode" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</spring:form>
</body>
</html>

jsp\hello.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>Insert title here</title>
</head>
<body>
    <h1>Welcome to Spring MVC training on ${dateVisited}</h1>
    <BR/>
<a href="/Spring3Demo/hello/welcome.htm">Click welcome</a><br/>
<a href="/Spring3Demo/hello/customerform.htm">Customer form</a>
</body>
</html>

jsp\customersuccess.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>Insert title here</title>
</head>
<body>
Customer Success!!!!!
<BR/>
<a href="/Spring3Demo/hello/welcome.htm">Click welcome</a><br/>
<a href="/Spring3Demo/hello/customerform.htm">Customer form</a>
</body>
</html>

src\messages.properties
=============================================================

NotEmpty.cusromer.customerName=Customer name is required
Size.cusromer.customerName=Customer name max size is 16
Size.cusromer.location=Customer location is required
Range.Size.cusromer.customerCode= Customer code must between 1 to 150