-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurso Spring Boot, MVC com Ajax - DataTables.txt
409 lines (308 loc) · 15.1 KB
/
Curso Spring Boot, MVC com Ajax - DataTables.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
1. Inclua a referência das bibliotecas do datatable dentro da sua página HTML:
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
2. Confira se a página está como abaixo:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Spring Boot + JPA + Datatables TESTE</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- As bibliotecas .css e .js abaixo servem para colocar as colunas da datatable que não cabem na linha,
ocasionando o scroll, deixando elas escondidas com a opção de consulta las através do botão mais que
aparece automaticamente ao utilizar essas bibliotecas.
-->
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.5/css/responsive.dataTables.min.css" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script
src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="js/datatable.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.5/js/dataTables.responsive.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6">
<h1>Employees Table</h1>
<!-- as classes display e nowrap server para deixar a datatable responsiva -->
<table id="employeesTable" class="display nowrap">
<!-- Header Table -->
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
</thead>
<!-- Footer Table -->
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</body>
</html>
2. (Client) Nas configurações do datatable, no javascript do cliente deixe da seguinte forma:
$(document).ready( function () {
$('#employeesTable').DataTable({
processing : true,
serverSide : true, // Importante para informar qq operação de paging, searching, etc será submitido ao servidor
responsive : true,
lengthMenu : [ 5, 10, 20 ],
ajax: {
url : '/employees',
data : 'data' // Importante que o json criado pelo servidor venha dentro de uma estrutura, neste caso nomeado como "data"
},
"language" : {
"url" : "../docs/portuguese.json"
},
"contentType" : "application/json; charset=utf-8",
columns : [
{ "data": "id"},
{ "data": "name" },
{ "data": "lastName" },
{ "data": "email" },
{ "data": "phone" },
{ "data": "active" }
]
/*
,colReorder: true,
"columnDefs": [{
"className": "small",
"targets": "_all"
} ],
*/
});
});
3. (Server) Crie a classe abaixo dentro do projeto:
// Esta classe trata as requisições feitas pelo datatable
package net.service;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import net.model.Employee;
import net.repository.EmployeeRepository;
public class EmployeeDataTablesService {
private String[] cols = { "id", "name", "lastName", "email", "phone", "active" };
public Map< String, Object> execute( EmployeeRepository repository, HttpServletRequest request ){
int start = Integer.parseInt( request.getParameter("start") );
int length = Integer.parseInt( request.getParameter("length"));
int draw = Integer.parseInt( request.getParameter("draw"));
int current = currentPage( start, length );
String column = columnName(request);
Sort.Direction direction = orderBy( request );
String search = searchBy(request);
Pageable pageable = PageRequest.of(current, length, direction, column);
Page<Employee> page = queryBy( search, repository, pageable );
Map<String, Object> json = new LinkedHashMap<>();
json.put("draw", draw);
json.put("recordsTotal",page.getTotalElements());
json.put("recordsFiltered", page.getTotalElements());
json.put("data", page.getContent());
return json;
}
private String searchBy( HttpServletRequest request) {
return request.getParameter( "search[value]").isEmpty() ? "" : request.getParameter("search[value]" );
}
private Page<Employee> queryBy(String search, EmployeeRepository repository, Pageable pageable) {
if (search.isEmpty()) {
return repository.findAll(pageable);
}
return repository.findByNameOrLastNameOrEmailOrPhone(search, pageable);
}
private Direction orderBy(HttpServletRequest request) {
String order = request.getParameter("order[0][dir]");
Sort.Direction sort = Sort.Direction.ASC;
if ( order.equalsIgnoreCase("desc")) {
sort = Sort.Direction.DESC;
}
return sort;
}
private String columnName(HttpServletRequest request) {
int iCol = Integer.parseInt( request.getParameter("order[0][column]"));
return cols[iCol];
}
private int currentPage(int start, int length) {
return start/length;
}
public EmployeeDataTablesService() {
// TODO Auto-generated constructor stub
}
}
4. (Resource) Na classe Resource deixe da seguinte forma:
// Aqui que é feito a intersecção do javascript client datatable com o servidor
/*
$(document).ready( function () {
$('#employeesTable').DataTable({
...
ajax: {
url : '/employees', // é o mesmo pathname do "RequestMapping"
data : 'data'
},
*/
@RequestMapping(path = "/employees", method = RequestMethod.GET)
public ResponseEntity<?> getAllEmployees( HttpServletRequest request ){
Map<String, Object> data = new EmployeeDataTablesService().execute(repository, request);
return ResponseEntity.ok(data);
}
5. Deixando responsivo a página HTML:
. Coloque os links abaixo na página HTML:
<script src="https://cdn.datatables.net/responsive/2.2.5/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.5/css/responsive.dataTables.min.css" />
. Associe a classe "nowrap" na table da datatable dentro da página HTML:
<!-- nowrap faz com que o tamanho das colunas da datatable se ajuste ao tamanho do conteúdo da informação -->
<table id="employeesTable" class="display nowrap">
. Ao incluir o script cdn e o css já realiza o efeito de espansão (+) em cada linha para as colunas que não couberem
na tela.
6. Insira na classe repository um método que sirva para localizar as infs através de todos os parâmetros eleitos para busca.
Qdo houver a digitação no campo de busca do datatable, o método selecionará através dos principais campos desejados para
realizar a busca:
@Repository("employeeRepository")
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
@Query("Select e from Employee e " +
"where e.name like %:search% " +
" or e.lastName like %:search% " +
" or e.email like %:search% " +
" or e.phone like %:search%")
Page<Employee> findByNameOrLastNameOrEmailOrPhone( @Param("search") String search, Pageable pageable );
}
. Para o sistema sair da datatable e chegar nesse ponto do projeto fará os seguintes passos:
. sempre que for digitado alguma coisa no campo de busca será chamado o método "/employees" visto anteriormente.
$('#employeesTable').DataTable({
...
ajax: {
url : '/employees', // é o mesmo pathname do "RequestMapping"
data : 'data'
},
. Passa o controle para o controller:
@RequestMapping(path = "/employees", method = RequestMethod.GET)
public ResponseEntity<?> getAllEmployees( HttpServletRequest request ){
Map<String, Object> data = new EmployeeDataTablesService().execute(repository, request);
return ResponseEntity.ok(data);
}
. Que passa ao service:
public Map< String, Object> execute( EmployeeRepository repository, HttpServletRequest request ){
...
Page<Employee> page = queryBy( search, repository, pageable );
...
}
private Page<Employee> queryBy(String search, EmployeeRepository repository, Pageable pageable) {
if (search.isEmpty()) {
return repository.findAll(pageable);
}
return repository.findByNameOrLastNameOrEmailOrPhone(search, pageable);
}
. Que passará para o método do repository:
@Repository("employeeRepository")
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
@Query("Select e from Employee e " +
"where e.name like %:search% " +
" or e.lastName like %:search% " +
" or e.email like %:search% " +
" or e.phone like %:search%")
Page<Employee> findByNameOrLastNameOrEmailOrPhone( @Param("search") String search, Pageable pageable );
// O @Param encarrega-se de injetar o valor passado como parâmetro para dentro da String do @Query fazendo
// uma substituição do parâmetro :search
}
8. Caso houver necessidade de trabalhar com valores, ou números, no datatable assista a aula 61. Filtrando por preço.
Encontreremos também como fazer para renderizar valores com máscara.
9. Formatando valores datas no datatable:
. Acessar a página www.momentjs.com. Existem dois tipos de bibliotecas para ser baixado neste link:
. moment.min.js - Independente do local
. moment-with-locales.min.js - Lib de um determinado local
. Ao invés de baixar a biblioteca do site momentjs podemos fazer uso do cdn:
. Acesse o site https://cdnjs.com, localize o cdn da biblioteca momentjs e copie para dentro da página do projeto:
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment-with-locales.min.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment-with-locales.min.js"></script>
. Acesse a declaração do datatable, altere a renderização como feito no campo datNasc abaixo e informe o locale "moment.locale("pt-br")
$(document).ready(function() {
moment.locale("pt-br"); // Declaração do locale Brasil
...
$('#pessoaTable').DataTable( {
"destroy" : true,
"scrollY" : "300px",
"scrollX" : true,
"select" : true,
"serverSide" : false,
"sAjaxDataProp" : "data",
"scrollCollapse" : true,
"info" : false,
"language" : {
"decimal" : ",",
"thousands" : "."
},
"pagingType" : "full_numbers",
"language" : {
"url" : "../docs/portuguese.json"
},
"sPaginationType" : "bootstrap",
"contentType" : "application/json; charset=utf-8",
"aLengthMenu" : [ [ 5, 10, 20, 100, -1 ],
[ 5, 10, 20, 100, "Todos" ] ],
"pageLength": 5,
"lengthChange" : true,
"processing" : true,
"serverSide" : false,
"ajax": {
"url": "../pessoa/api",
"type": "GET",
"data": {
'cpf': $('#cpf-busca').val(),
'nome': $('#nome-busca').val()
},
"dataType": "json"
},
"columns": [
{"defaultContent":"<div class='text-center'>"+
"<div class='btn-group'>"+
"<button class='btn btn-light btn-sm btnEditar'><i class='material-icons'>edit</i></button> "+
"<button class='btn btn-light btn-sm btnBorrar'><i class='material-icons'>delete</i></button>"+
"</div>"+
"</div>"},
{ "data" : "sequencial" },
{ "data" : "cpf" },
{ "data" : "nome" },
{ "data" : "endereco" },
{"data" : "cidade" },
{ "data" : "estado" },
{ "data" : "cep" },
{"data" : "datNasc",
render: function(datNasc){
return moment(datNasc).format("L"); // Renderização de campos datas
}
},
{"data" : "foneRes"},
{"data" : "salario", render: $.fn.dataTable.render.number( '.', ',', 2, 'R$' )} // Renderização de campos numéricos
],
"columnDefs": [{
"className": "small",
"targets": "_all"
} ],
select: true,
colReorder: true,
} );