client side pagination dan sorting spring mvc datatables

membuat paging (pagination) dan sorting, spring mvc + datatables + bootstrap

Bismillah

q> Melanjukan tulisan sebelumnya
https://saifiahmada.wordpress.com/2014/12/27/client-side-validator-menggunakan-jquery-validation/

q> Hasil yang akan didapat pada tulisan kali ini  :

Selection_641

q> Langkah2 praktek :

1. buat bean entity User

package com.saifiahmada.maven.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotBlank;

@Entity
public class User {

	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy="uuid2")
	private String id;
	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String username;

	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String password;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

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

}

2. buat interface UserRepository

package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.User;

public interface UserRepository extends JpaRepository<User, String>  {

}

3. buat class UserService

package com.saifiahmada.maven.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.saifiahmada.maven.entity.Partner;
import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.repository.UserRepository;

@Service
public class UserService {

	@Autowired
	private UserRepository userRepository;

	public List<User> findAll() {
		return userRepository.findAll();
	}

	public void save(User user) {
		userRepository.save(user);
	}

	public User findOne(String id) {
		return userRepository.findOne(id);
	}

	public void delete(String id) {
		userRepository.delete(id);
	}

}

4. buat class UserController

package com.saifiahmada.maven.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;

	@RequestMapping(value="/form", method=RequestMethod.GET)
	public String form(Model model){
		model.addAttribute("entity", new User());
		return "user-form";
	}

	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){
		model.addAttribute("entities", userService.findAll());
		return "user-list";
	}

	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String add(@Valid @ModelAttribute("entity") User user, BindingResult result) {

		if (result.hasErrors()) {
			return "user-form";
		}
		userService.save(user);
		return "redirect:/user/form.html?success=true";
	}

	@RequestMapping(value="/edit/{id}")
	public String edit(@PathVariable("id") String id, Model model){
		model.addAttribute("entity", userService.findOne(id));
		return "user-form";
	}

	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable("id") String id, Model model){
		userService.delete(id);
		model.addAttribute("entity", new User());
		model.addAttribute("listModel", userService.findAll());
		return "user-form";
	}

}

5. buat file user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp" %>

<a href="/user/form.html" class="btn btn-success">Add</a>
<br/>
<br/>

<table id="entity" class="table table-bordered table-hover table-striped">
	<thead>
		<tr>
			<th>Username</th>
			<th>Password</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${entities}" var="l">
			<tr>
				<td>${l.username }</td>
				<td>${l.password }</td>
				<td><a href="/user/edit/${l.id}.html">Edit</a></td>
				<td><a href="/user/delete/${l.id}.html">Delete</a></td>
			</tr>
		</c:forEach>
	</tbody>
</table>

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

6. buat file user-form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<c:if test="${param.success eq true }">
	<div class="alert alert-success">Data berhasil disimpan</div>
</c:if>

<form:form commandName="entity" action="/user/add.html"
	cssClass="form-horizontal formUser">

	<c:if test="${ ! empty entity.id}">
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">Id</label>
			<div class="col-sm-10">
				<form:input path="id" cssClass="form-control" readonly="true" disabled="true" />
				<form:hidden path="id"/>
			</div>
		</div>
	</c:if>

	<div class="form-group">
		<label for="username" class="col-sm-2 control-label">Username</label>
		<div class="col-sm-10">
			<form:input path="username" cssClass="form-control" />
			<form:errors path="username" />
		</div>
	</div>

	<div class="form-group">
		<label for="password" class="col-sm-2 control-label">Password</label>
		<div class="col-sm-10">
			<form:input path="password" cssClass="form-control" />
			<form:errors path="password" />
		</div>
	</div>

	<input type="submit" value="Simpan" class="btn btn-success" />
	<a href="/user/form.html" class="btn btn-success">Reset</a>
	<a href="/user/list.html" class="btn btn-success">List</a>

</form:form>

<script type="text/javascript" >
	$(document).ready( function() {

		$(".formUser").validate(
			{
				rules : {
					username : {
						required : true,
						minlength : 3
					},
					password : {
						required : true,
						minlength : 3
					}

				},
				highlight : function (element) {
					$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
				},
				unhighlight : function (element) {
					$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
				}
			}
		);

	} );
</script>

7. tambahkan definition pada file general.xml

<definition name="user-list" extends="common">
		<put-attribute name="title" value="User List" />
		<put-attribute name="body" value="/WEB-INF/jsp/user-list.jsp" />
		<put-attribute name="current" value="user-list" />
	</definition>

	<definition name="part-form" extends="common">
		<put-attribute name="title" value="Part Form" />
		<put-attribute name="body" value="/WEB-INF/jsp/part-form.jsp" />
		<put-attribute name="current" value="part-list" />
	</definition>

8. tambahkan link untuk menu User pada file classic.jsp

<li class="${current == 'user-list' ? 'active' : '' }"><a href="/user/list.html">User</a></li>

9. pagination dan sorting pada sisi client (client side)

pada halaman user-list.jsp terdapat script javascript seperti ini

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

dari script di atas ada method DataTable(), method inilah yang membuat list user mempunyai paging dan sorting,
tetapi untuk script tersebut masih melakukan paging dan sorting dari sisi client (client side)

Berdasarkan http://www.datatables.net/
dijelaskan :

DataTables is a plug-in for the jQuery Javascript library.
It is a highly flexible tool, based upon the foundations of progressive enhancement,
and will add advanced interaction controls to any HTML table.

Untuk mengintegrasikan datatables dan bootstrap 3 (karena aplikasi ini menggunakan bootstrap 3) buka halaman ini
https://datatables.net/examples/styling/bootstrap.html

q> Untuk user-form.jsp juga sudah ada client validator

Selection_642

q> Tampilan ketika form berhasil disimpan

Selection_643

q> Sorting client side

Selection_644

Alhamdulillah

Published by

saifiahmada

Begin a big Process with a bit trying

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s