Friday 29 December 2017

How to Remove duplicates from ArrayList in Java

     I have shared the code to remove duplicates from ArrayList with primitive and custom objects. You can use set interface class, so it can not add elements to the class.

1) Remove duplicates from ArrayList with String as Generics.

Example:--

package com.test;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicates {
 
      public static void main(String[] args) {
  
            List<String> list = new ArrayList<String>();
            list.add("Mahesh");
            list.add("Nagesh");
            list.add("Lohit");
            list.add("Mahesh"); 
            System.out.println("List with duplicates:");
            for (String name : list) {
                 System.out.println(name);
            }
  
            /* Convert list to LinkedHashSet, to preserve the insertion 
              order and remove the duplicates */
  
            Set<String> set = new LinkedHashSet<String>(list);
            System.out.println("Set with unique elements:");
            for (String name: set) {
                 System.out.println(name);
            }
      }
}

Output :--
List with duplicates:
Mahesh
Nagesh
Lohit
Mahesh
Set with unique elements:
Mahesh
Nagesh
Lohit


2) Remove duplicates from ArrayList with Custom Object as Employee

Example:--
Employee class is as below, override equals and hashCode methods.

package com.test;

public class Employee {
 
     private int empId;
     private String empName;
 
     public Employee(int empId, String empName) {
          this.empId = empId;
          this.empName = empName;
     }
 
     public int getEmpId() {
          return empId;
     }
     public void setEmpId(int empId) {
          this.empId = empId;
     }
     public String getEmpName() {
          return empName;
     }
     public void setEmpName(String empName) {
          this.empName = empName;
     }
 
     @Override
     public int hashCode() {
          return this.empId;
     }
 
     @Override
     public boolean equals(Object obj) {
          if (obj instanceof Employee) {
               return ((Employee)obj).empId == this.empId;
          }
          return false;
    }
}

Main class ,

package com.test;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class RemoveCustomDuplicates {
 
      public static void main(String[] args) {
  
            Employee emp1 = new Employee(1, "Kiran");
            Employee emp2 = new Employee(2, "Mahesh");
            Employee emp3 = new Employee(3, "Lakshmi");
            Employee emp4 = new Employee(1, "Kiran");
  
            List<Employee> list = new ArrayList<Employee>();
  
            list.add(emp1);
            list.add(emp2);
            list.add(emp3);
            list.add(emp4); 
            System.out.println("List with duplicates:");
            for (Employee emp : list) {
                 System.out.println(emp.getEmpName());
            }
  
            /* Convert list to LinkedHashSet, to preserve the insertion 
             order and remove the duplicates */
  
           Set<Employee> set = new LinkedHashSet<Employee>(list);
           System.out.println("Set with unique elements:");
           for (Employee emp: set) {
                System.out.println(emp.getEmpName());
           }
      }

}

Output : --
List with duplicates:
Kiran
Mahesh
Lakshmi
Kiran
Set with unique elements:
Kiran
Mahesh
Lakshmi

Thanks for visiting blog.


Related Posts:--
1) Internal implementation of ArrayList in Java
2) Java Program to Count Occurrence of Word in a Sentence
3) How to iterate the TreeMap in reverse order in Java
4) Example to sort keys of TreeMap using Comparator with Custom Object
5) Internal implementation of ArrayList in Java

Tuesday 12 December 2017

HTTP Status Codes

    When browser requests a service from web server, it will return some status code. I have listed all HTTP Status codes as below,

  • 1xx -  Informational


100 - Continue - The server has received the request headers, and the client should proceed to send
 the request body

101 - Switching Protocols -  The Server switches protocol.


  • 2xx - Successful 

 200 - OK      -  This is a successful HTTP request

201 - Created  -  Request is completed, new resource is created.

202 - AcceptedThe request is accepted for processing, but the processing is not complete.

203 - Non-Authoritative Information -  The information in the entity header is from a local or third party copy, not from the original server.

204 - No Content  -  A status code and a header are given in the response, but there is no entity-body in the reply.

205 - Reset Content - Browser will clear the form data.

206 - Partial Content - The server is delivering only part of the resource due to a range header sent by the client

  •  3xx - Redirection


300 - Multiple Choices - A link list. The user can select a link and go to that location. Maximum five addresses  .

301 - Moved Permanently - Requested page permanently moved to new URL.

302 - Found - Requested page temporarily moved to new URL.

303 - See other - Requested page can be found some other URL.

304 - Not Modified - Requested has not modified.

305 - Use Proxy - The requested URL must be accessed through the proxy mentioned in the Location header.

306 - Unused - This code was used in a previous version. It is no longer used, but the code is reserved. 

307 - Temporary Redirection - The requested page has moved temporarily to a new URL

  • 4xx - Client error

400 - Bad Request - The Request can not be fulfilled because of some bad syntax.

401 - Unauthorized - The request has not been applied because it lacks valid authentication credentials for the target resource.

402 - Payment Required - Now you can not use this code.

403 - Forbidden - The request is a legal request, but the server is refusing to respond to it due to some factor.

404 - Page Not Found - Requested page is not found.

405 - Method Not Allowed - Method specified in the request is not allowed

406 - Not Acceptable - Generated server response not accepts the client.

407 - Proxy Authentication Required - The client must first authenticate itself with the proxy 

408 - Request Timeout - The Server time out waiting for the request

409 - Conflict - The request could not be completed because of a conflict.

410 - Gone - The requested page is no longer available.

411 - Length Required - The server refuses to accept the request without a defined Content-Length.

412 - Pre condition failed - The precondition given in the request evaluated to false by the server 

413 - Request Entity too large - The server will not accept the request, because the request entity is  too large.

414 -  Request URI too long - The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information .

415 -  Unsupported Media Type - If media type is not supported, it won't accept the request.

416 - Request range not satisfiable - The client has asked for a portion of the file, but the server cannot supply that portion

417 - Exception failed - The server cannot meet the requirements of the Expect request-header field


  • 5xx - Server Error

500 - Internal Server Error - The request was not completed.  The server met an unexpected condition.

501 - Not Implemented - The server does not support the functionality required to fulfill the request. 

 502 - Bad Gateway - The server, while acting as a gateway or proxy, received an invalid response  from an inbound server it accessed while attempting to fulfill the request. 

503 - Service Unavailable - The server is currently unavailable

504 - Gateway Timeout - The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.

505 - HTTP Version not supported - The server does not support the HTTP protocol version used in the request.

Related Post : - 

Monday 11 December 2017

Java Program to Count Occurrence of Word in a Sentence

     In this post, we can learn how to count the word occurrences in a given String. In this code, first split the String sentence using space as delimiter . Use any map to store the word as a key and number occurrence as value in the Integer form.

See the below code,

package com.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WordsOccurances {

     public static void main(String[] args) {
  
          String sentence = "Java can run on many different operating "
              + "systems. This makes Java platform independent.";
  
          String[] words = sentence.split(" ");
          Map<String, Integer> wordsMap = new HashMap<String, Integer>();
  
          for (int i = 0; i<words.length; i++ ) {
              if (wordsMap.containsKey(words[i])) {
                   Integer value = wordsMap.get(words[i]);
                   wordsMap.put(words[i], value + 1);
              } else {
                   wordsMap.put(words[i], 1);
              }
          }
  
            /*Now iterate the HashMap to display the word with number 
             of time occurance    */
  
          Iterator it = wordsMap.entrySet().iterator();
          while (it.hasNext()) {
               Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
               System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
                    +entryKeyValue.getValue()+" times");
          }
     }
} 
 
 
Output :-- 
Word : Java, Occurance : 2 times
Word : can, Occurance : 1 times
Word : systems., Occurance : 1 times
Word : independent., Occurance : 1 times
Word : makes, Occurance : 1 times
Word : This, Occurance : 1 times
Word : run, Occurance : 1 times
Word : operating, Occurance : 1 times
Word : many, Occurance : 1 times
Word : different, Occurance : 1 times
Word : platform, Occurance : 1 times
Word : on, Occurance : 1 times 

Related Post :--
1) String Related Interview Questions  
2) How HashMap works internally in Java?  
3) How to iterate the TreeMap in reverse order in Java  
4) Collection Interview Questions and Answers in Java(List,Map & Set)
5) Exception Handling Interview questions and answers
6) Spring @Qualifier Annotation with example

Thursday 7 December 2017

Example to sort keys of TreeMap using Comparator with Custom Object

        In the below code, we are passing custom object as key in TreeMap i.e Employee user defined class. In this case, we need to pass the comparator object in the constructor, while creating the TreeMap object.  In the Comparator, need to override the compare method and to write the sorting logic.

 Example:--

package com.test;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapSorting { 
 
     public static void main(String[] args) { 
 
           TreeMap<Employee, String> treeMap = new TreeMap<Employee, String>(new MyNameComp()); 
 
           treeMap.put(new Employee(10,  "Anil"), "one");
           treeMap.put(new Employee(10,  "Mahesh"), "two");
           treeMap.put(new Employee(10,  "John"), "three");
           treeMap.put(new Employee(10,  "Nagesh"), "four");
           for (Map.Entry<Employee, String> map : treeMap.entrySet()) {
                 System.out.println("Key : ("+map.getKey()+ "), Value : "+ map.getValue());
           }
     }
}
 
class Employee { 
 
     private Integer id;
     private String name; 
 
     public Employee(Integer id, String name) {
          this.id = id;
          this.name = name;
     }
     public Integer getId() {
          return id;
     }
     public void setId(Integer id) {
          this.id = id;
     }
     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
     public String toString() {
          return this.name+":"+id;
     }
}

class MyNameComp implements Comparator<Employee> {

     public int compare(Employee o1, Employee o2) {
            return o1.getName().compareTo(o2.getName());
     }
 
}

Output : -Key : (Anil:10), Value : one
               Key : (John:10), Value : three
              Key : (Mahesh:10), Value : two
              Key : (Nagesh:10), Value : four



Related Post :--
How to iterate the TreeMap in reverse order in Java  
Internal Implementation of TreeMap in Java  
Internal Implementation of LinkedList in Java  
Internal implementation of ArrayList in Java  
How HashMap works internally in Java?  

Tuesday 5 December 2017

How to iterate the TreeMap in reverse order in Java

      The TreeMap will give the sorting order i.e natural sorting.  It will sort the key based on Comparator passed in the constructor while creating the TreeMap.
      But If you want to iterate the TreeMap in reverse order then pass Collections.reverseOrder() argument in the constructor of  TreeMap.

Signature of reverseOrder() method as,

public static Comparator reverseOrder():

        Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface

Example: --

package com.test;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class SortTreeMap {

      public static void main(String[] args) {
  
             TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(
                                          Collections.reverseOrder());
  
             //add elements into the Map
             treeMap.put("Mahesh", 1);
             treeMap.put("Anil", 2);
             treeMap.put("Raj", 3);
             treeMap.put("Anand", 4);
  
             Iterator it = treeMap.entrySet().iterator();
  
             while (it.hasNext()) {
                   Map.Entry mp = (Map.Entry) it.next();
                   System.out.println("Key :" +mp.getKey()+"  Value: "+mp.getValue());
             }
      }
}

Output:--Key :Raj  Value: 3
              Key :Mahesh  Value: 1
              Key :Anil  Value: 2
              Key :Anand  Value: 4


Related Post:--
Internal Implementation of TreeMap in Java 
How HashMap works internally in Java?  
Internal implementation of ArrayList in Java  
Internal Implementation of LinkedList in Java  

Saturday 2 December 2017

Spring MVC with Hibernate CRUD Example

      In this post, We can write a simple Spring MVC web application i.e CRUD operation using annotation based Hibernate ORM.  The CRUD operation means Add, Edit, Select and Delete. We can create web application using Spring and Hibernate as follows.

First step is to create the Dynamic Web Project in Eclipse , then configure the web.xml as follows,
The project structure i.e folder structure shown in the below image.

 Project Structure:--

Spring Crud operation project structure

Deployment Descriptor(web.xml)
 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
      <servlet-name>appln</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>/WEB-INF/appln-servlet.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
        <servlet-name>appln</servlet-name>
        <url-pattern>*.html</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
        <welcome-file>add.html</welcome-file>
 </welcome-file-list>

</web-app>

       In the above configuration, most important is to give the correct spring bean configuration location otherwise it won't take configuration file. In this example, appln-servlet.xml is the bean configuration file kept inside WEB-INF folder.


Hibernate Entity Bean:--

 In the example, used annotation based Hibernate not xml configuration. The Annotation based Employee bean is as follows,


package com.adnblog.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Anil N
 *
 */
@Entity
@Table(name="Employee")
public class Employee implements Serializable{

        private static final long serialVersionUID = -723583058586873479L;
 
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        @Column(name = "emp_id")
        private Integer empId;
 
        @Column(name="emp_name")
        private String empName;
 
        @Column(name="emp_address")
        private String empAddress;
 
        @Column(name="emp_salary")
        private Long salary;
 
        @Column(name="emp_age")
        private Integer empAge;

        public Integer getEmpId() {
             return empId;
        }

        public void setEmpId(Integer empId) {
             this.empId = empId;
        }

        public String getEmpName() {
             return empName;
        }

        public void setEmpName(String empName) {
             this.empName = empName;
        }

        public String getEmpAddress() {
             return empAddress;
        }

        public void setEmpAddress(String empAddress) {
             this.empAddress = empAddress;
        }

        public Long getSalary() {
             return salary;
        }

        public void setSalary(Long salary) {
             this.salary = salary;
        }

        public Integer getEmpAge() {
             return empAge;
        }

        public void setEmpAge(Integer empAge) {
             this.empAge = empAge;
        }
}

The entity bean Employee maps with database employee table. So I'm creating an employee table is as follows.

employee table - Using PostgreSQL database.

CREATE TABLE employee (
         emp_id INTEGER PRIMARY KEY,
         emp_address CHARACTER VARYING(40),
         emp_salary BIGINT,
         emp_age INTEGER,
         emp_name CHARACTER VARYING(25)
);

create one properties file under resource folder i.e database.properties, there keep all database information as a key value pairs, and this information you can access in the bean configuration file.

database.properties

database.driver=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/hms
database.user=postgres
database.password=admin
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

using PostgreSQL as database, you can use any database and configure here properly.


Hibernate DAO Class: - 

          We will create the EmployeeDao interface to declare the methods that are used in the CRUD example. Next we can implement those methods in another class.

EmployeeDao.java


package com.adnblog.dao;

import java.util.List;

import com.adnblog.model.Employee;

/**
 * @author Anil N
 *
 */
public interface EmployeeDao {
 
       public Integer addEmployee(Employee employee);

       public List<Employee> listEmployeess();
 
       public Employee getEmployee(int empid);
 
       public void updateEmployee(Employee employee);
 
       public void deleteEmployee(Employee emp);
}

Implementation class i.e EmployeeDaoImpl as follows,

EmployeeDaoImpl.java
 
package com.adnblog.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.adnblog.model.Employee;

/**
 * @author Anil N
 *
 */
@Repository
public class EmployeeDaoImpl implements EmployeeDao {

       @Autowired
       private SessionFactory sessionFactory;
 
       public Integer addEmployee(Employee employee) {
            return (Integer)sessionFactory.getCurrentSession().save(employee);
       }

       public void updateEmployee(Employee employee) {
            sessionFactory.getCurrentSession().saveOrUpdate(employee);
       }
       @SuppressWarnings("unchecked")
       public List<Employee> listEmployeess() {
            return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
       }

       public Employee getEmployee(int empid) {
            return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
       }

       public void deleteEmployee(Employee emp) {
             sessionFactory.getCurrentSession().createQuery("DELETE FROM Employee WHERE emp_id = "+emp.getEmpId()).executeUpdate();
       }

}

We are using Spring transaction so Hibernate transaction not required.


Service Classes :--

       In Service also I created one interface, there I declared all CRUD methods. Next in implemented class implemented all methods and used Spring transaction.


EmployeeService.java


package com.adnblog.service;

import java.util.List;

import com.adnblog.model.Employee;

/**
 * @author Anil N
 *
 */
public interface EmployeeService {
 
      public Integer addEmployee(Employee employee);

      public List<Employee> listEmployeess();
 
      public Employee getEmployee(int empid);
 
      public void updateEmployee(Employee employee);
 
      public void deleteEmployee(Employee emp);
}

The implemented Service class i.e EmployeeServiceImpl is as follows, (@Transactional annotation is using for declarative transaction)

EmployeeServiceImpl.java

package com.adnblog.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adnblog.dao.EmployeeDao;
import com.adnblog.model.Employee;

/**
 * @author Anil N
 *
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements EmployeeService {

       @Autowired
       private EmployeeDao employeeDao;
 
       @Transactional(propagation = Propagation.REQUIRED)
       public Integer addEmployee(Employee employee) {
            return employeeDao.addEmployee(employee);
       }
 
       public List<Employee> listEmployeess() {
            return employeeDao.listEmployeess();
       }

       public Employee getEmployee(int empid) {
            return employeeDao.getEmployee(empid);
       }
       @Transactional(propagation = Propagation.REQUIRED)
       public void updateEmployee(Employee employee) {
            employeeDao.updateEmployee(employee);
       }
 
       @Transactional(propagation = Propagation.REQUIRED)
       public void deleteEmployee(Employee emp) {
            employeeDao.deleteEmployee(emp);
       }

}



Controller class:--
        The Controller class is a heart of MVC pattern, using @Controller annoation Front controller finds the appropriate controller using HandlerMapping.  It will take the request, process it and send model data to the appropriate view.

EmployeeController.java  


package com.adnblog.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.adnblog.bean.EmployeeBean;
import com.adnblog.model.Employee;
import com.adnblog.service.EmployeeService;

/**
 * @author Anil N
 *
 */
@Controller
public class EmployeeController {
 
       @Autowired
       private EmployeeService employeeService;
 
       @RequestMapping(value = "/add", method = RequestMethod.GET)
       public ModelAndView addEmployee(@ModelAttribute("command")  EmployeeBean employeeBean,
                        BindingResult result) {
             Map<String, Object> model = new HashMap<String, Object>();
             model.put("employee",  new EmployeeBean());
             return new ModelAndView("addEmployee", model);
       }

       @RequestMapping(value = "/edit", method = RequestMethod.GET)
       public ModelAndView editEmployee(@RequestParam("id") Integer id, 
                         @ModelAttribute("command") EmployeeBean employeeBean) {
              Map<String, Object> model = new HashMap<String, Object>();
              model.put("employee",  new EmployeeBean());
              model.put("employees", employeeService.getEmployee(id));
              return new ModelAndView("addEmployee", model);
       }
 
 
       @RequestMapping(value = "/save", method = RequestMethod.POST)
       public ModelAndView saveEmployee(@RequestParam("id") String id,
                          @ModelAttribute("command") EmployeeBean employeeBean) {
  
              Integer empId = 0;
              Employee employee = prepareModel(employeeBean, id);
              if (id != null && !id.isEmpty()) {
                     employeeService.updateEmployee(employee);
                     empId = Integer.parseInt(id);
              } else {
                     empId = employeeService.addEmployee(employee);
              }
              ModelAndView mv = new ModelAndView("redirect:/edit.html?id="+empId);
              return mv;
       }

       @RequestMapping(value="/list", method = RequestMethod.GET)
       public ModelAndView listEmployees() { 
              Map<String, Object> model = new HashMap<String, Object>();
              model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
              return new ModelAndView("employeesList", model);
       }

       @RequestMapping(value = "/delete", method = RequestMethod.GET)
       public ModelAndView deleteEmployee(@RequestParam("id") String id) {
              Employee emp =  new Employee();
              emp.setEmpId(Integer.parseInt(id));
              employeeService.deleteEmployee(emp);
              return new ModelAndView("redirect:/list.html");
       }
 
       private Employee prepareModel(EmployeeBean employeeBean, String id){
              Employee employee = new Employee();
              employee.setEmpAddress(employeeBean.getEmpAddress());
              employee.setEmpAge(employeeBean.getEmpAge());
              employee.setEmpName(employeeBean.getEmpName());
              employee.setSalary(employeeBean.getSalary());
              if (id != null && !id.isEmpty()) {
                    employee.setEmpId(Integer.parseInt(id));
              } else {
                    employee.setEmpId(employeeBean.getEmpId());
              }
              return employee;
       }

       private List<EmployeeBean> prepareListofBean(List<Employee> employees){
              List<EmployeeBean> beans = null;
              if(employees != null && !employees.isEmpty()){
                    beans = new ArrayList<EmployeeBean>();
                    EmployeeBean bean = null;
                    for(Employee employee : employees){
                          bean = new EmployeeBean();
                          bean.setEmpName(employee.getEmpName());
                          bean.setEmpId(employee.getEmpId());
                          bean.setEmpAddress(employee.getEmpAddress());
                          bean.setSalary(employee.getSalary());
                          bean.setEmpAge(employee.getEmpAge());
                          beans.add(bean);
                     }
               }
               return beans;
       }
}



Spring Bean Configuration (appln-servlet.xml)
         Next create one xml file under WEB-INF folder, give same file name whatever in the web.xml.
This configuration file config the bean and view using some tags. The appln-servlet.xml file is as follows.

appln-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:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <context:property-placeholder location="classpath:resources/database.properties" />
 <context:component-scan base-package="com.adnblog" />

 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${database.driver}" />
      <property name="url" value="${database.url}" />
      <property name="username" value="${database.user}" />
      <property name="password" value="${database.password}" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="annotatedClasses">
         <list>
             <value>com.adnblog.model.Employee</value>
         </list>
      </property>
      <property name="hibernateProperties">
          <props>
              <prop key="hibernate.dialect">${hibernate.dialect}</prop>
              <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
              <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>    
         </props>
     </property>
 </bean>

 <bean id="hibernateTransactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
           <property name="sessionFactory" ref="sessionFactory" />
 </bean>
 
 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
               value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
 </bean>
</beans>



View(Jsp page): - 
         I have created two JSP here, addEmployee.jsp and employeeList.jsp. The addEmployee.jsp is using for adding and editing the employee details, employeeList.jsp is for displaying the employee list and delete the particular employee from the list.
created under pages folder of WEB-INF,   

addEmployee.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
  <c:set var="addOrEdit" value="Add" />
  <c:set var="submit" value="Submit"/>
  <c:if test="${employees.empId != null}">
   <c:set var="addOrEdit" value="Edit" />
   <c:set var="submit" value="Update"/>
  </c:if>
  <title>Spring MVC Add/Edit Operation</title>
 </head>
 <body>
  <h2>${addOrEdit} Employee Data</h2>
  <form:form method="POST" action="/WebAppln/save.html?id=${employees.empId}" commandName="command">
      <table>
       <tr>
           <td><form:label path="empId">Employee ID:</form:label></td>
           <td><c:out value="${employees.empId}"/>
           <form:hidden path="empId" /></td>
       </tr>
       <tr>
           <td><form:label path="empName">Employee Name:</form:label></td>
           <td><form:input path="empName" value="${employees.empName}"/></td>
       </tr>
       <tr>
           <td><form:label path="empAge">Employee Age:</form:label></td>
           <td><form:input path="empAge" value="${employees.empAge}"/></td>
       </tr>
       <tr>
           <td><form:label path="salary">Employee Salary:</form:label></td>
           <td><form:input path="salary" value="${employees.salary}"/></td>
       </tr>
       
       <tr>
           <td><form:label path="empAddress">Employee Address:</form:label></td>
                    <td><form:input path="empAddress" value="${employees.empAddress}"/></td>
       </tr>
       <tr><td></td>
         <td colspan="2"><input type="submit" value="${submit}"/>&nbsp; &nbsp; &nbsp;<b><a href="/WebAppln/list.html" >List Of Employee</a></b></td>
        </tr>
   </table> 
  </form:form>
 </body>
</html>

employeeList.jsp
 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>All Employees</title>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;
}
</style>
</head>
<body>
    <h1>List Employees</h1>
    <c:if test="${empty employees}">
       <h3>No Records found!</h3>
   </c:if>

    <c:if test="${!empty employees}">
 <table align="left" width="100%">
  <tr>
   <th>Employee ID</th>
   <th>Employee Name</th>
   <th>Employee Age</th>
   <th>Employee Salary</th>
   <th>Employee Address</th> 
                        <th></th>
                        <th></th>
  </tr>

  <c:forEach items="${employees}" var="employee">
   <tr>
    <td><c:out value="${employee.empId}"/></td>
    <td><c:out value="${employee.empName}"/></td>
    <td><c:out value="${employee.empAge}"/></td>
    <td><c:out value="${employee.salary}"/></td>
    <td><c:out value="${employee.empAddress}"/></td> 
                                <td><b><a href="/WebAppln/edit.html?id=${employee.empId}">Edit</a></b></td>
                                <td><b><a href="/WebAppln/delete.html?id=${employee.empId}">Delete</a></b></td>
   </tr>
  </c:forEach>
 </table><br/>
</c:if>
<table style="border: none;">
 <tr>
  <td style="padding : none; border: none;"><h3><a href="/WebAppln/add.html">Add More Employee</a></h3></td>
 </tr>
</table>
</body>
</html>



Running the application using Tomcat Server or any Server:--
        If you run the given application without spcifying the URL, it will execute the welcome file i.e add.html so by default add employee will call.



List of Employee : -


Edit screen:--

 Thank you for visiting blog...



Related post :
Spring Annotations
Spring MVC workflow with example  
What is dependency Injection in Spring ? give me types and advantages with examples  
What are different Spring Bean Scopes?
What is Autowiring in Spring ? Explain Autowiring modes and limitations with examples
Spring @Qualifier Annotation with example
Spring Configuration Metadata (XML, Annotation and Java)