Skip to content

Commit e68e747

Browse files
committed
10_01_HW9_binding_ajax
1 parent 80bc814 commit e68e747

12 files changed

Lines changed: 161 additions & 140 deletions

File tree

‎src/main/java/ru/javawebinar/topjava/model/Meal.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import org.hibernate.annotations.OnDelete;
55
import org.hibernate.annotations.OnDeleteAction;
66
import org.hibernate.validator.constraints.Range;
7+
import org.springframework.format.annotation.DateTimeFormat;
78

89
import javax.persistence.*;
910
import javax.validation.constraints.NotBlank;
@@ -32,6 +33,7 @@ public class Meal extends AbstractBaseEntity {
3233

3334
@Column(name = "date_time", nullable = false)
3435
@NotNull
36+
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
3537
private LocalDateTime dateTime;
3638

3739
@Column(name = "description", nullable = false)
@@ -40,8 +42,9 @@ public class Meal extends AbstractBaseEntity {
4042
private String description;
4143

4244
@Column(name = "calories", nullable = false)
45+
@NotNull
4346
@Range(min = 10, max = 5000)
44-
private int calories;
47+
private Integer calories;
4548

4649
@ManyToOne(fetch = FetchType.LAZY)
4750
@JoinColumn(name = "user_id", nullable = false)
@@ -88,7 +91,7 @@ public void setDescription(String description) {
8891
this.description = description;
8992
}
9093

91-
public void setCalories(int calories) {
94+
public void setCalories(Integer calories) {
9295
this.calories = calories;
9396
}
9497

‎src/main/java/ru/javawebinar/topjava/util/ValidationUtil.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package ru.javawebinar.topjava.util;
22

3+
import org.springframework.http.ResponseEntity;
4+
import org.springframework.validation.BindingResult;
35
import ru.javawebinar.topjava.HasId;
46
import ru.javawebinar.topjava.util.exception.NotFoundException;
57

68
import javax.validation.*;
79
import java.util.Set;
10+
import java.util.stream.Collectors;
811

912
public class ValidationUtil {
1013

@@ -62,4 +65,12 @@ public static void assureIdConsistent(HasId bean, int id) {
6265
throw new IllegalArgumentException(bean + " must be with id=" + id);
6366
}
6467
}
68+
69+
public static ResponseEntity<String> getErrorResponse(BindingResult result) {
70+
return ResponseEntity.unprocessableEntity().body(
71+
result.getFieldErrors().stream()
72+
.map(fe -> String.format("[%s] %s", fe.getField(), fe.getDefaultMessage()))
73+
.collect(Collectors.joining("<br>"))
74+
);
75+
}
6576
}

‎src/main/java/ru/javawebinar/topjava/web/RootController.java‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,13 @@
22

33
import org.slf4j.Logger;
44
import org.slf4j.LoggerFactory;
5-
import org.springframework.beans.factory.annotation.Autowired;
65
import org.springframework.stereotype.Controller;
7-
import org.springframework.ui.Model;
86
import org.springframework.web.bind.annotation.GetMapping;
9-
import ru.javawebinar.topjava.service.MealService;
10-
import ru.javawebinar.topjava.util.MealsUtil;
117

128
@Controller
139
public class RootController {
1410
private static final Logger log = LoggerFactory.getLogger(RootController.class);
1511

16-
@Autowired
17-
private MealService mealService;
18-
1912
@GetMapping("/")
2013
public String root() {
2114
log.info("root");
@@ -35,10 +28,8 @@ public String login() {
3528
}
3629

3730
@GetMapping("/meals")
38-
public String getMeals(Model model) {
31+
public String getMeals() {
3932
log.info("meals");
40-
model.addAttribute("meals",
41-
MealsUtil.getTos(mealService.getAll(SecurityUtil.authUserId()), SecurityUtil.authUserCaloriesPerDay()));
4233
return "meals";
4334
}
4435
}

‎src/main/java/ru/javawebinar/topjava/web/meal/MealUIController.java‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
package ru.javawebinar.topjava.web.meal;
22

3-
import org.springframework.format.annotation.DateTimeFormat;
43
import org.springframework.http.HttpStatus;
54
import org.springframework.http.MediaType;
5+
import org.springframework.http.ResponseEntity;
66
import org.springframework.lang.Nullable;
7+
import org.springframework.validation.BindingResult;
78
import org.springframework.web.bind.annotation.*;
89
import ru.javawebinar.topjava.model.Meal;
910
import ru.javawebinar.topjava.to.MealTo;
11+
import ru.javawebinar.topjava.util.ValidationUtil;
1012

13+
import javax.validation.Valid;
1114
import java.time.LocalDate;
12-
import java.time.LocalDateTime;
1315
import java.time.LocalTime;
1416
import java.util.List;
1517

@@ -23,6 +25,12 @@ public List<MealTo> getAll() {
2325
return super.getAll();
2426
}
2527

28+
@Override
29+
@GetMapping( "/{id}")
30+
public Meal get(@PathVariable int id) {
31+
return super.get(id);
32+
}
33+
2634
@Override
2735
@DeleteMapping("/{id}")
2836
@ResponseStatus(HttpStatus.NO_CONTENT)
@@ -32,10 +40,16 @@ public void delete(@PathVariable int id) {
3240

3341
@PostMapping
3442
@ResponseStatus(HttpStatus.NO_CONTENT)
35-
public void create(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateTime,
36-
@RequestParam String description,
37-
@RequestParam int calories) {
38-
super.create(new Meal(null, dateTime, description, calories));
43+
public ResponseEntity<String> createOrUpdate(@Valid Meal meal, BindingResult result) {
44+
if (result.hasErrors()) {
45+
return ValidationUtil.getErrorResponse(result);
46+
}
47+
if (meal.isNew()) {
48+
super.create(meal);
49+
} else {
50+
super.update(meal, meal.getId());
51+
}
52+
return ResponseEntity.ok().build();
3953
}
4054

4155
@Override

‎src/main/java/ru/javawebinar/topjava/web/user/AdminUIController.java‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
import org.springframework.web.bind.annotation.*;
88
import ru.javawebinar.topjava.model.User;
99
import ru.javawebinar.topjava.to.UserTo;
10+
import ru.javawebinar.topjava.util.ValidationUtil;
1011

1112
import javax.validation.Valid;
1213
import java.util.List;
13-
import java.util.stream.Collectors;
1414

1515
@RestController
1616
@RequestMapping(value = "/admin/users", produces = MediaType.APPLICATION_JSON_VALUE)
@@ -38,10 +38,7 @@ public void delete(@PathVariable int id) {
3838
@PostMapping
3939
public ResponseEntity<String> createOrUpdate(@Valid UserTo userTo, BindingResult result) {
4040
if (result.hasErrors()) {
41-
String errorFieldsMsg = result.getFieldErrors().stream()
42-
.map(fe -> String.format("[%s] %s", fe.getField(), fe.getDefaultMessage()))
43-
.collect(Collectors.joining("<br>"));
44-
return ResponseEntity.unprocessableEntity().body(errorFieldsMsg);
41+
return ValidationUtil.getErrorResponse(result);
4542
}
4643
if (userTo.isNew()) {
4744
super.create(userTo);

‎src/main/resources/logback.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
<logger name="ru.javawebinar.topjava" level="debug"/>
2424
<!--<logger name="org.springframework.web.servlet" level="debug"/>-->
2525
<logger name="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver" level="debug"/>
26-
<logger name="org.springframework.security" level="debug"/>
26+
<!-- <logger name="org.springframework.security" level="debug"/>-->
2727

2828
<root level="info">
2929
<appender-ref ref="file"/>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
2+
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
3+
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
4+
5+
<script type="text/javascript">
6+
const i18n = {}; // https://learn.javascript.ru/object
7+
<%-- user.add/user.edit or meal.add/meal.edit --%>
8+
i18n["addTitle"] = '<spring:message code="${param.page}.add"/>';
9+
i18n["editTitle"] = '<spring:message code="${param.page}.edit"/>';
10+
11+
<c:forEach var='key' items='${["common.deleted", "common.saved", "common.enabled", "common.disabled", "common.errorStatus", "common.confirm"]}'>
12+
i18n['${key}'] = '<spring:message code="${key}"/>';
13+
</c:forEach>
14+
</script>

‎src/main/webapp/WEB-INF/jsp/meals.jsp‎

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,21 +62,6 @@
6262
<th></th>
6363
</tr>
6464
</thead>
65-
<c:forEach items="${requestScope.meals}" var="meal">
66-
<jsp:useBean id="meal" type="ru.javawebinar.topjava.to.MealTo"/>
67-
<tr data-meal-excess="${meal.excess}">
68-
<td>
69-
<%--${meal.dateTime.toLocalDate()} ${meal.dateTime.toLocalTime()}--%>
70-
<%--<%=TimeUtil.toString(meal.getDateTime())%>--%>
71-
<%--${fn:replace(meal.dateTime, 'T', ' ')}--%>
72-
${fn:formatDateTime(meal.dateTime)}
73-
</td>
74-
<td>${meal.description}</td>
75-
<td>${meal.calories}</td>
76-
<td><a><span class="fa fa-pencil"></span></a></td>
77-
<td><a onclick="deleteRow(${meal.id})"><span class="fa fa-remove"></span></a></td>
78-
</tr>
79-
</c:forEach>
8065
</table>
8166
</div>
8267
</div>
@@ -85,7 +70,7 @@
8570
<div class="modal-dialog">
8671
<div class="modal-content">
8772
<div class="modal-header">
88-
<h4 class="modal-title" id="modalTitle"><spring:message code="meal.add"/></h4>
73+
<h4 class="modal-title" id="modalTitle"></h4>
8974
<button type="button" class="close" data-dismiss="modal" onclick="closeNoty()">&times;</button>
9075
</div>
9176
<div class="modal-body">
@@ -126,4 +111,7 @@
126111
</div>
127112
<jsp:include page="fragments/footer.jsp"/>
128113
</body>
114+
<jsp:include page="fragments/i18n.jsp">
115+
<jsp:param name="page" value="meal"/>
116+
</jsp:include>
129117
</html>

‎src/main/webapp/WEB-INF/jsp/users.jsp‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,7 @@
7878
</div>
7979
<jsp:include page="fragments/footer.jsp"/>
8080
</body>
81-
<script type="text/javascript">
82-
const i18n = {}; // https://learn.javascript.ru/object
83-
i18n["addTitle"] = '<spring:message code="user.add"/>';
84-
i18n["editTitle"] = '<spring:message code="user.edit"/>';
85-
86-
<c:forEach var="key" items='${["common.deleted","common.saved","common.enabled","common.disabled","common.errorStatus","common.confirm"]}'>
87-
i18n["${key}"] = "<spring:message code="${key}"/>";
88-
</c:forEach>
89-
</script>
81+
<jsp:include page="fragments/i18n.jsp">
82+
<jsp:param name="page" value="user"/>
83+
</jsp:include>
9084
</html>

‎src/main/webapp/resources/js/topjava.common.js‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
let form;
22

3-
function makeEditable(datatableApi) {
4-
ctx.datatableApi = datatableApi;
3+
function makeEditable(datatableOpts) {
4+
ctx.datatableApi = $("#datatable").DataTable(
5+
{
6+
...datatableOpts, // https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax
7+
"ajax": {
8+
"url": ctx.ajaxUrl,
9+
"dataSrc": ""
10+
},
11+
"paging": false,
12+
"info": true
13+
}
14+
);
515
form = $('#detailsForm');
616

717
$(document).ajaxError(function (event, jqXHR, options, jsExc) {

0 commit comments

Comments
 (0)