spring+4+mvc+pagination+data+tables
Click here to download eclipse supported ZIP file
This is result.jsp JSP file and it is used display the output for the application.
| <%@ 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">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC pagination using data tables</title>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<script type="text/javascript">
//Plug-in to fetch page data
jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( objValues )
{
return {
"iStart": objValues._iDisplayStart,
"iEnd": objValues.fnDisplayEnd(),
"iLength": objValues._iDisplayLength,
"iTotal": objValues.fnRecordsTotal(),
"iFilteredTotal": objValues.fnRecordsDisplay(),
"iPage": objValues._iDisplayLength === -1 ?
0 : Math.ceil( objValues._iDisplayStart / objValues._iDisplayLength ),
"iTotalPages": objValues._iDisplayLength === -1 ?
0 : Math.ceil( objValues.fnRecordsDisplay() / objValues._iDisplayLength )
};
};
$(document).ready(function() {
$("#example").dataTable( {
"bProcessing": true,
"bServerSide": true,
"sort": "position",
//bStateSave variable you can use to save state on client cookies: set value "true"
"bStateSave": false,
//Default: Page display length
"iDisplayLength": 10,
//We will use below variable to track page number on server side(For more information visit: http://legacy.datatables.net/usage/options#iDisplayStart)
"iDisplayStart": 0,
"fnDrawCallback": function () {
//Get page numer on client. Please note: number start from 0 So
//for the first page you will see 0 second page 1 third page 2...
//Un-comment below alert to see page number
//alert("Current page number: "+this.fnPagingInfo().iPage);
},
"sAjaxSource": "springPaginationDataTables.html",
"aoColumns": [
{ "mData": "name" },
{ "mData": "position" },
{ "mData": "office" },
{ "mData": "phone" },
{ "mData": "start_date" },
{ "mData": "salary" },
]
} );
} );
</script>
</head>
<body>
<form:form action="" method="GET">
<h2 >Spring 4 MVC pagination using data tables<br><br></h2>
<table width="70%" style="border: 3px;background: rgb(243, 244, 248);"><tr><td>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Phone</th>
<th>Start Date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</td></tr></table>
</form:form>
</body>
</html>
|
This is Employee.java file having the source code to execute business logic.
package com.cv.spring.controller;
/**
* @author Chandra Vardhan
*/
public class Employee {
private String name;
private String position;
private String office;
private String phone;
private String start_date;
private String salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
} |
This is EmployeeJsonObject.java file having the source code to execute business logic.
package com.cv.spring.controller;
import java.util.List;
/**
* @author Chandra Vardhan
*/
public class EmployeeJsonObject {
int iTotalRecords;
int iTotalDisplayRecords;
String sEcho;
String sColumns;
List<Employee> aaData;
public int getiTotalRecords() {
return iTotalRecords;
}
public void setiTotalRecords(int iTotalRecords) {
this.iTotalRecords = iTotalRecords;
}
public int getiTotalDisplayRecords() {
return iTotalDisplayRecords;
}
public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
this.iTotalDisplayRecords = iTotalDisplayRecords;
}
public String getsEcho() {
return sEcho;
}
public void setsEcho(String sEcho) {
this.sEcho = sEcho;
}
public String getsColumns() {
return sColumns;
}
public void setsColumns(String sColumns) {
this.sColumns = sColumns;
}
public List<Employee> getAaData() {
return aaData;
}
public void setAaData(List<Employee> aaData) {
this.aaData = aaData;
}
} |
This is SpringDataTableController.java file having the controller logic and it will have the services defined in it.
package com.cv.spring.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* @author Chandra Vardhan
*/
@Controller
public class SpringDataTableController {
private final static Logger LOGGER = Logger.getLogger(SpringDataTableController.class);
@RequestMapping(value = "/result.html", method =
RequestMethod.GET)
public String printWelcome(@ModelAttribute("employee") Employee employee, BindingResult result,ModelMap model, HttpServletRequest
request, HttpServletResponse response) {
LOGGER.info("Entered into SpringDataTableController.printWelcome()");
return "result";
}
@RequestMapping(value = "/springPaginationDataTables.html", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody String springPaginationDataTables(HttpServletRequest request) throws IOException {
LOGGER.info("Entered into SpringDataTableController.springPaginationDataTables(-)");
//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/10)+1;
//Fetch search parameter
String searchParameter = request.getParameter("sSearch");
//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));
//Create page list data
List<Employee> employeesList = createPaginationData(pageDisplayLength);
//Here is server side pagination logic. Based on the page number you could make call
//to the data base create new list and send back to the client. For demo I am shuffling
//the same list to show data randomly
if (pageNumber == 1) {
Collections.shuffle(employeesList);
}else if (pageNumber == 2) {
Collections.shuffle(employeesList);
}else {
Collections.shuffle(employeesList);
}
//Search functionality: Returns filtered list based on search parameter
employeesList = getListBasedOnSearchParameter(searchParameter,employeesList);
EmployeeJsonObject employeeJsonObject = new EmployeeJsonObject();
//Set Total display record
employeeJsonObject.setiTotalDisplayRecords(500);
//Set Total record
employeeJsonObject.setiTotalRecords(500);
employeeJsonObject.setAaData(employeesList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(employeeJsonObject);
LOGGER.info("Exiting from SpringDataTableController.springPaginationDataTables(-)");
return json2;
}
private List<Employee> getListBasedOnSearchParameter(String searchParameter,List<Employee> employeesList) {
LOGGER.info("Entered into SpringDataTableController.getListBasedOnSearchParameter(-)");
if (null != searchParameter && !searchParameter.equals("")) {
List<Employee> employeesListForSearch = new ArrayList<Employee>();
searchParameter = searchParameter.toUpperCase();
for (Employee employee : employeesList) {
if (employee.getName().toUpperCase().indexOf(searchParameter)!= -1 || employee.getOffice().toUpperCase().indexOf(searchParameter)!= -1
|| employee.getPhone().toUpperCase().indexOf(searchParameter)!= -1 || employee.getPosition().toUpperCase().indexOf(searchParameter)!= -1
|| employee.getSalary().toUpperCase().indexOf(searchParameter)!= -1 || employee.getStart_date().toUpperCase().indexOf(searchParameter)!= -1) {
employeesListForSearch.add(employee);
}
}
employeesList = employeesListForSearch;
employeesListForSearch = null;
}
LOGGER.info("Exiting from SpringDataTableController.getListBasedOnSearchParameter(-)");
return employeesList;
}
private List<Employee> createPaginationData(Integer pageDisplayLength) {
List<Employee> employeesList = new ArrayList<Employee>();
for (int i = 0; i < 1; i++) {
Employee employee2 = new Employee();
employee2.setName("Chandra Vardhan");
employee2.setPosition("System Architect");
employee2.setSalary("RS520800");
employee2.setOffice("IN");
employee2.setPhone("999999999");
employee2.setStart_date("09/01/2016");
employeesList.add(employee2);
employee2 = new Employee();
employee2.setName("James Gosling");
employee2.setPosition("Solution Architect");
employee2.setSalary("$1340800");
employee2.setOffice("NY");
employee2.setPhone("987897899");
employee2.setStart_date("05/05/2016");
employeesList.add(employee2);
employee2 = new Employee();
employee2.setName("Java CV");
employee2.setPosition("Architect");
employee2.setSalary("$380,800");
employee2.setOffice("SJ");
employee2.setPhone("1234567890");
employee2.setStart_date("02/02/2016");
employeesList.add(employee2);
}
for (int i = 0; i < pageDisplayLength-5; i++) {
Employee employee2 = new Employee();
employee2.setName("Rod Johnson");
employee2.setPosition("System Architect");
employee2.setSalary("$1320800");
employee2.setOffice("US");
employee2.setPhone("999999999");
employee2.setStart_date("01/08/2016");
employeesList.add(employee2);
}
return employeesList;
}
} |
This is pom.xml file having the entries of dependency jars and information to build the application .
| <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">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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.spring</groupId>
<artifactId>Spring4MVCPaginationDataTables</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>SpringPaginationDataTables Maven Webapp</name>
http://maven.apache.org
<properties>
<spring.version>4.2.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
test
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<finalName>Spring4MVCPaginationDataTables</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project> |
This is dispatcher-servlet.xml spring configuration file and these entries are used in the application.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.cv.spring.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
|
This is web.xml deployment descriptor file and it describes how the web application should be deployed.
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>result.html</welcome-file> </welcome-file-list> </web-app>
|
This is log4j.properties file having the entries for logging the information into the console/file.
#By default enabling Console appender # Root logger option log4j.rootLogger=INFO, stdout
# Redirect log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n
# Redirect log messages to a log file #log4j.appender.file=org.apache.log4j.RollingFileAppender #log4j.appender.file.File=C:\servlet-application.log #log4j.appender.file.MaxFileSize=5MB #log4j.appender.file.MaxBackupIndex=10 #log4j.appender.file.layout=org.apache.log4j.PatternLayout #log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
Great Article
ReplyDeleteFinal Year Projects for CSE in Angularjs
Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai