Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Showing posts with label Programs. Show all posts
Showing posts with label Programs. Show all posts

Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

Saturday, September 19, 2015

Remove duplicate record in table

In this post, we are going to see how to remove duplicate records from table.

Create a test table
mysql> CREATE TABLE test_table (`id` int(11) DEFAULT NULL,`name` varchar(10) DEFAULT NULL);
Insert duplicate values in test table.
mysql> insert into test_table values (1,'aaa'),(1,'aaa'),(1,'aaa'),(1,'bbb'),(1,'bbb'),(1,'bbb');
mysql> select * from test_table;
+------+------+
| id | name |
+------+------+
| 1 | aaa |
| 1 | aaa |
| 1 | aaa |
| 1 | bbb |
| 1 | bbb |
| 1 | bbb |
+------+------+
Remove duplicate rows from test table
mysql> alter IGNORE table test_table add UNIQUE key (id,name);
Records: 6 Duplicates: 4 Warnings: 0
mysql> select * from test_table ;
+------+------+
| id | name |
+------+------+
| 1 | aaa |
| 1 | bbb |
+------+------+

Saturday, September 5, 2015

Spring 4 MVC + Hibernate 4 + MySQL 5 + Maven 3 integration : CRUD operations example

In this post, we are going to learn how to integrate Spring4 MVC with Hibernate4 application with Maven build tool and will perform CRUD operations using MySql Database.
Project Structure:
The following screenshot shows final structure of the project:

Tools and Technologies:

  • Spring 4.1.5 RELEASE
  • Hibernate 4.3.8 Final
  • MySQL 5.1.10
  • Java 8
  • Eclipse
  • Tomcat 8
  • Maven 3

Step 1: Create Database Table
For this demo, i have created a Employees table in MySQL database. Find the script to create the Employees table.
create database ranga;
create table Employees (
id bigint not null auto_increment,
age integer,
name varchar(255),
salary float,
primary key (id)
)
Step 2: Updating the Maven Dependencies
Update pom.xml to include required dependencies
pom.xml
<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>com.ranga</groupId>
<artifactId>Spring4Hiberante4Integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring4Hiberante4Integration</name>

<!-- Specifying the Versions of Spring, Hiberante, MySQL etc -->
<properties>
<spring.version>4.1.5.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<mysql.version>5.1.10</mysql.version>
<junit-version>4.11</junit-version>
<servlet-api-version>3.1.0</servlet-api-version>
<jsp-version>2.1</jsp-version>
<jstl-version>1.2</jstl-version>
<java.version>1.8</java.version>
</properties>

<!-- Specifying the Dependencies -->
<dependencies>

<!-- Spring 4 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

<!-- Hibernate 4 dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!--MYSQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>

<!-- Servlet and JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-version}</version>
<scope>provided</scope>
</dependency>

<!-- JSTL dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl-version}</version>
</dependency>

<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<finalName>Spring4Hiberante4Integration</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>

</project>
Step 3: Deployment Descriptor (web.xml)
We need to plugin spring framework in our web application, that is done by configuring Spring framework DispatcherServlet as front controller.

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>Spring4 MVC Hibernate4 Application</display-name>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Step 4: Spring Configuration file (mvc-dispatcher-servlet.xml)
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>


<!-- Specifying base package of the Components like Controller, Service,
DAO -->

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


<!-- Getting Database properties -->
<context:property-placeholder location="classpath:application.properties" />

<mvc:annotation-driven />

<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

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

<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">

<property name="driverClass" value="${database.driverClass}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />

<property name="acquireIncrement" value="${connection.acquireIncrement}" />
<property name="minPoolSize" value="${connection.minPoolSize}" />
<property name="maxPoolSize" value="${connection.maxPoolSize}" />
<property name="maxIdleTime" value="${connection.maxIdleTime}" />
</bean>

<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.ranga.entity"></property>
</bean>

<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Step 5: Declaring the hibernate and database properties
application.properties
#Database related properties
database.driverClass=com.mysql.jdbc.Driver
database.url=jdbc:mysql:///ranga
database.username=ranga
database.password=ranga

#Hibernate related properties
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true

#Connection pool related properties
connection.acquireIncrement=2
connection.minPoolSize=20
connection.maxPoolSize=50
connection.maxIdleTime=600
Step 6:  Persistence Layer
Employee.java
package com.ranga.entity;

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

import java.io.Serializable;
/**
* @author Ranga Reddy
* @version 1.0
*
*/

@Entity
@Table(name = "Employees")
public class Employee implements Serializable {

private static final long serialVersionUID = -7988799579036225137L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column
private String name;

@Column
private int age;

@Column
private float salary;

public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
Step 7: Utility Class
HibernateUtil.java
package com.ranga.util;

import java.io.Serializable;
import java.util.List;

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

/**
* @author Ranga Reddy
* @version 1.0
*/

@Repository
public class HibernateUtil {

@Autowired
private SessionFactory sessionFactory;

public <T> Serializable create(final T entity) {
return sessionFactory.getCurrentSession().save(entity);
}

public <T> T update(final T entity) {
sessionFactory.getCurrentSession().update(entity);
return entity;
}

public <T> void delete(final T entity) {
sessionFactory.getCurrentSession().delete(entity);
}

public <T> void delete(Serializable id, Class<T> entityClass) {
T entity = fetchById(id, entityClass);
delete(entity);
}

@SuppressWarnings("unchecked")
public <T> List<T> fetchAll(Class<T> entityClass) {
return sessionFactory.getCurrentSession().createQuery(" FROM "+entityClass.getName()).list();
}

@SuppressWarnings("rawtypes")
public <T> List fetchAll(String query) {
return sessionFactory.getCurrentSession().createSQLQuery(query).list();
}

@SuppressWarnings("unchecked")
public <T> T fetchById(Serializable id, Class<T> entityClass) {
return (T)sessionFactory.getCurrentSession().get(entityClass, id);
}
}
Step 8: DAO Layer
EmployeeDAO.java
package com.ranga.dao;

import java.util.List;

import com.ranga.entity.Employee;

/**
* @author Ranga Reddy
* @version 1.0
*/

public interface EmployeeDAO {
public long createEmployee(Employee employee);
public Employee updateEmployee(Employee employee);
public void deleteEmployee(long id);
public List<Employee> getAllEmployees();
public Employee getEmployee(long id);
public List<Employee> getAllEmployees(String employeeName);
}
EmployeeDAOImpl.java
package com.ranga.dao.impl;

import com.ranga.dao.EmployeeDAO;
import com.ranga.entity.Employee;
import com.ranga.util.HibernateUtil;

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

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
* @author Ranga Reddy
* @version 1.0
*/


@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

public EmployeeDAOImpl() {
System.out.println("EmployeeDAOImpl");
}

@Autowired
private HibernateUtil hibernateUtil;

@Override
public long createEmployee(Employee employee) {
return (Long) hibernateUtil.create(employee);
}

@Override
public Employee updateEmployee(Employee employee) {
return hibernateUtil.update(employee);
}

@Override
public void deleteEmployee(long id) {
Employee employee = new Employee();
employee.setId(id);
hibernateUtil.delete(employee);
}

@Override
public List<Employee> getAllEmployees() {
return hibernateUtil.fetchAll(Employee.class);
}

@Override
public Employee getEmployee(long id) {
return hibernateUtil.fetchById(id, Employee.class);
}

@SuppressWarnings("unchecked")
@Override
public List<Employee> getAllEmployees(String employeeName) {
String query = "SELECT e.* FROM Employees e WHERE e.name like '%"+ employeeName +"%'";
List<Object[]> employeeObjects = hibernateUtil.fetchAll(query);
List<Employee> employees = new ArrayList<Employee>();
for(Object[] employeeObject: employeeObjects) {
Employee employee = new Employee();
long id = ((BigInteger) employeeObject[0]).longValue();
int age = (int) employeeObject[1];
String name = (String) employeeObject[2];
float salary = (float) employeeObject[3];
employee.setId(id);
employee.setName(name);
employee.setAge(age);
employee.setSalary(salary);
employees.add(employee);
}
System.out.println(employees);
return employees;
}
}
Step 8: Service Layer ( Service & Service Impl)

EmployeeService.java
package com.ranga.service;
import com.ranga.entity.Employee;

import java.util.List;

/**
* @author Ranga Reddy
* @version 1.0
*/

public interface EmployeeService {
public long createEmployee(Employee employee);
public Employee updateEmployee(Employee employee);
public void deleteEmployee(long id);
public List<Employee> getAllEmployees();
public Employee getEmployee(long id);
public List<Employee> getAllEmployees(String employeeName);
}
EmployeeServiceImpl.java
package com.ranga.service.impl;
import com.ranga.dao.EmployeeDAO;
import com.ranga.entity.Employee;
import com.ranga.service.EmployeeService;

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

import java.util.List;
/**
* @author Ranga Reddy
* @version 1.0
*/

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

public EmployeeServiceImpl() {
System.out.println("EmployeeServiceImpl()");
}

@Autowired
private EmployeeDAO employeeDAO;

@Override
public long createEmployee(Employee employee) {
return employeeDAO.createEmployee(employee);
}
@Override
public Employee updateEmployee(Employee employee) {
return employeeDAO.updateEmployee(employee);
}
@Override
public void deleteEmployee(long id) {
employeeDAO.deleteEmployee(id);
}
@Override
public List<Employee> getAllEmployees() {
return employeeDAO.getAllEmployees();
}
@Override
public Employee getEmployee(long id) {
return employeeDAO.getEmployee(id);
}
@Override
public List<Employee> getAllEmployees(String employeeName) {
return employeeDAO.getAllEmployees(employeeName);
}
}
Step 9: Controller Layer
EmployeeController.java
package com.ranga.controller;
import com.ranga.entity.Employee;
import com.ranga.service.EmployeeService;

import org.jboss.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
* @author Ranga Reddy
* @version 1.0
*/

@Controller
public class EmployeeController {

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

public EmployeeController() {
System.out.println("EmployeeController()");
}

@Autowired
private EmployeeService employeeService;

@RequestMapping("createEmployee")
public ModelAndView createEmployee(@ModelAttribute Employee employee) {
logger.info("Creating Employee. Data: "+employee);
return new ModelAndView("employeeForm");
}

@RequestMapping("editEmployee")
public ModelAndView editEmployee(@RequestParam long id, @ModelAttribute Employee employee) {
logger.info("Updating the Employee for the Id "+id);
employee = employeeService.getEmployee(id);
return new ModelAndView("employeeForm", "employeeObject", employee);
}

@RequestMapping("saveEmployee")
public ModelAndView saveEmployee(@ModelAttribute Employee employee) {
logger.info("Saving the Employee. Data : "+employee);
if(employee.getId() == 0){ // if employee id is 0 then creating the employee other updating the employee
employeeService.createEmployee(employee);
} else {
employeeService.updateEmployee(employee);
}
return new ModelAndView("redirect:getAllEmployees");
}

@RequestMapping("deleteEmployee")
public ModelAndView deleteEmployee(@RequestParam long id) {
logger.info("Deleting the Employee. Id : "+id);
employeeService.deleteEmployee(id);
return new ModelAndView("redirect:getAllEmployees");
}

@RequestMapping(value = {"getAllEmployees", "/"})
public ModelAndView getAllEmployees() {
logger.info("Getting the all Employees.");
List<Employee> employeeList = employeeService.getAllEmployees();
return new ModelAndView("employeeList", "employeeList", employeeList);
}

@RequestMapping("searchEmployee")
public ModelAndView searchEmployee(@RequestParam("searchName") String searchName) {
logger.info("Searching the Employee. Employee Names: "+searchName);
List<Employee> employeeList = employeeService.getAllEmployees(searchName);
return new ModelAndView("employeeList", "employeeList", employeeList);
}
}
Step 9: View Layer
employeeList.jsp
<%--
User: Ranga Reddy
Date: 09/05/2015
Time: 6:52 PM
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ 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=UTF-8">
<title>Employees List</title>
<!-- Bootstrap CSS -->
<%-- <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> --%>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style type="text/css">
.myrow-container {
margin: 20px;
}
</style>
</head>
<body class=".container-fluid">
<div class="container myrow-container">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
<div align="left"><b>Employees List</b> </div>
<div align="right"><a href="createEmployee">Add New Employee</a></div>
</h3>
</div>
<div class="panel-body">
<c:if test="${empty employeeList}">
There are no Employees
</c:if>
<c:if test="${not empty employeeList}">

<form action="searchEmployee">
<div class="row">
<div class="col-md-6"><div class="col-md-6">Search Employees:</div><div class="col-md-6"> <input type="text" name="searchName" id="searchName"> </div></div>
<div class="col-md-4"><input class="btn btn-success" type='submit' value='Search'/></div>
</div>
</form>

<table class="table table-hover table-bordered">
<thead style="background-color: #bce8f1;">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<c:forEach items="${employeeList}" var="emp">
<tr>
<th><c:out value="${emp.id}"/></th>
<th><c:out value="${emp.name}"/></th>
<th><c:out value="${emp.age}"/></th>
<th><c:out value="${emp.salary}"/></th>
<th><a href="editEmployee?id=<c:out value='${emp.id}'/>">Edit</a></th>
<th><a href="deleteEmployee?id=<c:out value='${emp.id}'/>">Delete</a></th>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<%-- <script src="<c:url value="/resources/js/jquery-2.1.3.js"/>"></script>
<script src="<c:url value="/resources/js/bootstrap.min.js"/>"></script>
--%>

</body>
</html>
employeeForm.jsp
<%--
User: Ranga Reddy
Date: 09/05/2015
Time: 6:52 PM
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ 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>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Ranga Reddy">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Information</title>
<!-- Bootstrap CSS -->
<%-- <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> --%>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style type="text/css">
.myrow-container{
margin: 20px;
}
</style>
</head>
<body class=".container-fluid">
<div class="container myrow-container">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
Employee Details
</h3>
</div>
<div class="panel-body">
<form:form id="employeeRegisterForm" cssClass="form-horizontal" modelAttribute="employee" method="post" action="saveEmployee">

<div class="form-group">
<div class="control-label col-xs-3"> <form:label path="name" >Name</form:label> </div>
<div class="col-xs-6">
<form:hidden path="id" value="${employeeObject.id}"/>
<form:input cssClass="form-control" path="name" value="${employeeObject.name}"/>
</div>
</div>

<div class="form-group">
<form:label path="age" cssClass="control-label col-xs-3">Age</form:label>
<div class="col-xs-6">
<form:input cssClass="form-control" path="age" value="${employeeObject.age}"/>
</div>
</div>

<div class="form-group">
<div class="control-label col-xs-3"><form:label path="salary">Salary</form:label></div>
<div class="col-xs-6">
<form:input cssClass="form-control" path="salary" value="${employeeObject.salary}"/>
</div>
</div>

<div class="form-group">
<div class="row">
<div class="col-xs-4">
</div>
<div class="col-xs-4">
<input type="submit" id="saveEmployee" class="btn btn-primary" value="Save" onclick="return submitEmployeeForm();"/>
</div>
<div class="col-xs-4">
</div>
</div>
</div>

</form:form>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<script type="text/javascript">
function submitEmployeeForm() {

// getting the employee form values
var name = $('#name').val().trim();
var age = $('#age').val();
var salary = $('#salary').val();
if(name.length ==0) {
alert('Please enter name');
$('#name').focus();
return false;
}

if(age <= 0) {
alert('Please enter proper age');
$('#age').focus();
return false;
}

if(salary <= 0) {
alert('Please enter proper salary');
$('#salary').focus();
return false;
}
return true;
};
</script>
</body>
</html>
Run the above Program:



     Searching Employee data:



Happy Learning!