Reputation: 8598
How can I allow empty input to field with type long in Spring MVC + thymeleaf?
I want this field to take default value. Currently I have the error:
Field error in object 'greeting' on field 'id': rejected value []; codes [typeMismatch.greeting.id,typeMismatch.id,typeMismatch.long,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [greeting.id,id]; arguments []; default message [id]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'long' for property 'id'; nested exception is java.lang.NumberFormatException: For input string: ""]]
when I try to submit form with empty id field
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
My POJO:
public class Greeting {
private long id;
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
My controller:
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {
return "result";
}
}
Upvotes: 0
Views: 1146
Reputation: 27
Had the same exact problem, fixed it using wrapper objects (Integer instead of int, Double instead of double, etc) in the POJO model classes.
Thanks Metroids for answer.
Upvotes: 0