В моем проекте Spring boot 2:
Модель:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Entity
public class Category {
@Id
@GeneratedValue
private int id;
@NotNull
private String name;
private String description;
@NotNull
private Date created;
private Date updated;
Здесь мой шаблон - категория. html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Category template title</title>
<link th:href="@{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<form method="post" action="#" th:object="${category}" th:action="@{/category}">
<h3>Category</h3>
<input type="hidden" id="id" th:field="*{id}"/>
<input type="text" placeholder="name" id="name" th:field="*{name}"/>
<input type="hidden" placeholder="created" id="created" th:field="*{created}"/>
<textarea placeholder="Description of the category" rows="5" id="description"
th:field="*{description}"></textarea>
<input type="submit" value="Submit"/>
</form>
<div class="result_message" th:if="${submitted}">
<h3>Your category has been submitted.</h3>
<p>Find all categories <a href="/categories">here</a></p>
</div>
</div>
</body>
</html>
здесь результат сгенерирован html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="/public/style.css" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<form method="post" action="/category"><input type="hidden" name="_csrf" value="b578aef2-491c-4e1a-a3a5-72cb679c6222"/>
<h3>Category</h3>
<input type="hidden" id="id" name="id" value="2"/>
<input type="text" placeholder="name" id="name" name="name" value="Electronics"/>
<input type="hidden" placeholder="created" id="created" name="created" value="2020-01-08 13:46:39.787"/>
<textarea placeholder="Description of the category" rows="5" id="description" name="description">Electronics's description</textarea>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>
А вот контроллер:
@Controller
public class CategoryController {
private CategoryRepository categoryRepository;
private static Logger logger = LogManager.getLogger(CategoryController.class);
// If class has only one constructore then @Autowired wiil execute automatically
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
createStubCategoryList();
}
@GetMapping("/categories")
public String getCategories(Model model) {
model.addAttribute("categoryList", categoryRepository.findAll());
return "categories";
}
@RequestMapping("category/edit/{id}")
public String editCategory(@PathVariable("id") int id, Model model) {
Optional<Category> category = categoryRepository.findById(id);
logger.info("find_category = " + category);
model.addAttribute("category", category);
return "category";
}
@RequestMapping("category/delete/{id}")
public String deleteCategory(@PathVariable("id") int id) {
categoryRepository.deleteById(id);
return "redirect:/categories";
}
@PostMapping(value = "/category")
public String submitCategory(Category category, Model model) {
category.setUpdated(new Date());
logger.info("updateCategory = " + category);
model.addAttribute("submitted", true);
model.addAttribute("category", category);
categoryRepository.save(category);
return "category";
}
Но когда я пытаюсь нажать кнопку отправки на странице /category
, я получаю ошибку:
Это приложение не имеет явного сопоставления для / error, поэтому вы видите это как запасной вариант.
Wed Jan 08 13:52:21 EET 2020
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='category'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'category' on field 'created': rejected value [2020-01-08 13:46:39.787]; codes [typeMismatch.category.created,typeMismatch.created,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [category.created,created]; arguments []; default message [created]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'created'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.NotNull java.util.Date] for value '2020-01-08 13:46:39.787'; nested exception is java.lang.IllegalArgumentException]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)