Form input type DateTime using Thymeleaf + Spring MVC issue - spring

I am struggling to use a Java LocalDateTime scheduledDateTime in a Thymeleaf form and getting it back to save it in the database. I get the following error message :
Bean property 'campaignExecution' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
It is really due to the datetime field. If I remove it from the html form everything works fine and I see the data from the object created in the controller.
My object contains the following along with the getter and setter returning thetype (LocalDateTime) :
#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime scheduledDateTime;
My Controller initialize the value to now()
#RequestMapping({ "/campaign1"})
public String requestCampaign1(Model model) {
CampaignExecution ce = new CampaignExecution();
LocalDateTime localDateTime = LocalDateTime.now();
ce.setScheduledDateTime(localDateTime);
model.addAttribute("campaignExecution", ce);
And this is the form :
<form id="f" name="f" th:action="#{/campaign1}"
th:object="${campaignExecution}" method="post">
<div>
Schedule a date :
<input type="datetime-local" th:field=*{campaignExecution.scheduledDateTime} />
</div>
<hr>
<div>Parameters</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Much easier than I was thinking. For th:field you cannot use multiple object but only the "form object". I was using the full qualifier : object name.property name.

Related

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'date' in thymeleaf form

<form th:action="#{/hi}" th:object="${datum}" method="post">
<p>date : <input type="date" th:field="*{date}"/> </p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
Controller for form above
#PostMapping("/hi")
fun testum(#ModelAttribute datum: Datum) {
println(datum)
}
simple pojo class
class Datum(
#DateTimeFormat(pattern = "yyyy-MM-dd")
var date: LocalDate? = null
)
I am trying to send date in form but get this exception:
Resolved exception caused by Handler execution: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'datum' on field 'date': rejected value [2018-06-20]; codes [typeMismatch.datum.date,typeMismatch.date,typeMismatch.java.time.LocalDate,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [datum.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2018-06-20'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-06-20]]
But if I change type from LocalDate to String it works fine. I want to map date that is in form to date property of Datum class. can anyone help me with that? any links? thanks.
This link did not help me similar problem
It's an old question, but I'm leaving an answer just for future readers.
This is not an issue with thymeleaf, and more of an issue of #DateTimeFormat binding.
The example in the question above will work if the Datum class is changed like so:
Solution 1.
class Datum {
#DateTimeFormat(pattern = "yyyy-MM-dd")
var date: LocalDate? = null
}
note that the date field has been moved from declaring in the primary constructor into the class body.
(notice the change from Datum (...) to Datum {...})
Solution 2.
class Datum (
#field:DateTimeFormat(pattern = "yyyy-MM-dd") var date: LocalDate? = null
)
if you need to have it declared inside constructor due to having it as data class or other reasons, you have to annotate using use-site targets.
HOWEVER, beware that Solution 2 may not always work. I cannot reproduce in a sample project - but in a real-life project, there was an issue where #field:DateTimeFormat didn't correctly bind the request parameter string to the Date object. It sometimes worked and sometimes didn't, making it very tricky to debug.
When it didn't work, it spewed out errors like Validation failed for object='Datum'. Error count: 1, while reverting to Solution 1 instead always worked. Every time we compiled again, Solution 2 sometimes worked and randomly broke without any code changes.
We've resorted to strictly putting #DateTimeFormat annotated fields down to the class body declaration to insure it works.
I just created your example using this as controller:
#Controller
public class StackOverflow {
#GetMapping("/stack")
public String template(Model m) {
m.addAttribute("datum", new Datanum());
return "stackoverflow.html";
}
#PostMapping("/stack2")
public String testum(#ModelAttribute Datanum user) {
System.out.println(user.getDate());
return null;
}
}
this as view:
<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form th:action="#{/stack2}" th:object="${datum}" method="post">
<p>date : <input type="date" th:field="*{date}"/> </p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
and this as Bean
import java.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
public class Datanum{
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}
and it worked:
The difference I see is that you're using var on your Bean
var date: LocalDate? = null
I think that is Java 10, isn't it? why don't you try to use
the bean as I did , maybe that could help you.
instead of var use LocalDate
hope this works

Spring Boot error while submitting form

I'm trying to add a table to the database via a form. The entity being created is called Album and it has 2 fields, Artist and Genre. Each of these two are separate entities. These 2 fields are annotated with #ManyToOne
#ManyToOne
private Artist artist;
#ManyToOne
private Genre genre;
When I submit the form, this is the error im getting:
There was an unexpected error (type=Internal Server Error, status=500).
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringOptionFieldAttrProcessor' (album/add:52)
The following code is part of my controller:
#RequestMapping({"/add", "/add/"})
public String adminAlbumAdd(Model model) {
model.addAttribute("album", new Album());
model.addAttribute("artists", artistService.list());
model.addAttribute("genres", genreService.list());
return "album/add";
}
#RequestMapping( value = "/save", method = RequestMethod.POST )
public String save(#Valid Album album, BindingResult bindingResult, Model model) {
if(bindingResult.hasErrors()) {
model.addAttribute("artists", artistService.list());
model.addAttribute("genres", genreService.list());
return "album/add";
} else {
Album savedAlbum = albumService.save(album);
return "redirect:/album/view/" + savedAlbum.getAlbumId();
}
}
And the following code is part of the thymeleaf template:
<div th:class="form-group" th:classappend="${#fields.hasErrors('artist')}? 'has-error'">
<label class="col-sm-2 control-label">Artist <span class="required">*</span></label>
<div class="col-md-10">
<select class="form-control" th:field="*{artist}">
<option value="">Select Artist</option>
<option th:each="artist : ${artists}" th:value="${artist.artistId}" th:text="${artist.artistFirstName + ' ' + artist.artistFirstName}">Artists</option>
</select>
<span th:if="${#fields.hasErrors('artist')}" th:errors="*{artist}" th:class="help-block">Artist Errors</span>
</div>
</div>
<div th:class="form-group" th:classappend="${#fields.hasErrors('genre')}? 'has-error'">
<label class="col-sm-2 control-label">Genre <span class="required">*</span></label>
<div class="col-md-10">
<select class="form-control" th:field="*{genre}">
<option value="">Select Genre</option>
<option th:each="genre : ${genres}" th:value="${genre.genreName}" th:text="${genre.genreName}">Genres</option>
</select>
<span th:if="${#fields.hasErrors('genre')}" th:errors="*{genre}" th:class="help-block">Genre Errors</span>
</div>
</div>
What is causing this error ?
The issue turned out to be related to the repository. I was extending CrudRepository, but the id was of type int. Once i changed that, it worked.
Firstly, you might consider using same mapping for GET/POST requests as a standard like:
#GetMapping("/new")
...
#PostMapping("/new")
Also #Valid Album album parameter should be annotated as #ModelAttribute.
You should not add model attributes if binding result has errors. (Actually, you should not add any model attribute for a POST method.)
You should not create that savedAlbum object with albumService.save().
That method should be void.
I will advise against posting directly to your database object. You should rather create a DTO class, say AlbumDto, that will map the classes like so:
public class AlbumDto {
...
private long genreId;
private long artistId;
// Getters & Setters
}
You can then convert it to your Album object, lookup the corresponding Genre and Artist in your controller, set them on the Album object and then save.

Spring Thymeleaf prefill input with ZonedDateTime

Today I am having some trouble with java.time and Thymeleaf
I have a form allowing users to edit an object. I have to prefill the form inputs with the current attributes of the object. This works in most cases. The only case that does not work is when i try to fill a date input with the value of a ZonedDateTime.
Here is the input:
<input type="date" class="form-control" th:field="*{startDate}">
and here is the attribute declaration:
private ZonedDateTime startDate;
Do you have any ideas why this does not work?

BindingResult requires dates input even without not null or validation

I got an issue with a web application in Spring.
I am writing a search jsp form with related controller and service.
I do not need some datas to be necessary, and it goes all fine but dates.
It requires me to insert dates into dates input tags, if I leave that boxes empty I got an error in BindingResult and my search service stops.
Why does it not accept empty values?
In the domain the attributes are not set to NotNull, and I even remove the #Valid annotation from the service, but it does continues to ask me for some datas into that fields.
Can anyone try to explain me where should I look to solve this issue?
Here is the code:
jsp form:
<form:form commandName="colloquioRicerca" action="colloquio_ricerca" method="post">
<fieldset>
<legend>Cerca un colloquio</legend>
<p class="errorLine">
<form:errors path="codiceFiscale" cssClass="error"/>
</p>
<p>
<label for="codiceFiscale">Codice Fiscale del Docente: </label>
<form:input id="codiceFiscale" path="codiceFiscale" tabindex="1"/>
</p>
<h5>Ricerca avanzata:</h5>
<p>
<label for="nome">Nome:<br><small>(accetta parziali)</small> </label>
<form:input id="nome" path="nome" tabindex="2"/>
</p>
<p>
<label for="cognome">Cognome:<br><small>(accetta parziali)</small></label>
<form:input id="cognome" path="cognome" tabindex="3"/>
</p>
<p>
<label for="dataColloquio">Cerca per data: </label>
<form:input id="dataColloquio" path="dataColloquio" tabindex="4" placeholder="dd/MM/yyyy"/>
</p>
<p>Cerca per periodo:</p>
<p>
<label for="dataIniz">Dal:</label>
<form:input id="dataIniz" path="dataIniz" tabindex="5" placeholder="dd/MM/yyyy"/>
<label for="dataFin">Al:</label>
<form:input id="dataFin" path="dataFin" tabindex="6" placeholder="dd/MM/yyyy"/>
</p>
<p>
<label for="esitoColloquio">Al:</label>
<form:input id="esitoColloquio" path="esitoColloquio" tabindex="7" placeholder="dd/MM/yyyy"/>
<!--
<label for="esitoColloquio">Esito del Colloquio:</label>
<form:select id="esitoColloquio" name="esitoColloquio" path="esitoColloquio" tabindex="7">
<form:option value="positivo" >Positivo</form:option>
<form:option value="negativo" >Negativo</form:option>
<form:option value="altro"></form:option>
</form:select>-->
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="8">
<input id="submit" type="submit" tabindex="9"
value="Search">
</p>
</fieldset>
</form:form>
domain:
public class ColloquioSearch {
#Size(min=16, max=16)
private String codiceFiscale;
private String nome;
//#Size(min=1, max=50)
private String cognome;
private Date dataColloquio;
private Date dataIniz;
private Date dataFin;
private String esitoColloquio;
service:
public List<Colloquio> getAllColloquio()
throws SQLException {
List<Colloquio> result = new ArrayList<Colloquio>();
Statement s= con.createStatement();
ResultSet rs = s.executeQuery(
"SELECT doc.codice_fiscale, col.data_colloquio, col.esito_colloquio, col.note_colloquio FROM colloqui_pj col, docenti_pj doc where doc.id_docente=col.id_docente");
while(rs.next());{// il getTime per convertirla in util.date
result.add(new Colloquio(rs.getString(1), rs.getTime(2), rs.getString(3), rs.getString(4)));
System.out.println("rs has next");
}
return result;
}
search method called by submit button:
#RequestMapping(value="prova")
public String goSearch(Model model){
logger.info("here we are");
model.addAttribute("colloquioRicerca", new ColloquioSearch());
return "ColloquioSearchForm";
}
#RequestMapping(value="colloquio_ricerca")
public String cerca(#ModelAttribute ColloquioSearch colloquioRicerca, BindingResult br, Model model){
logger.info("modelattribute:"+colloquioRicerca.toString()+"/"+colloquioRicerca.getCodiceFiscale());
logger.info("entered");
if (br.hasErrors()) {
FieldError fieldError = br.getFieldError();
logger.info("Code:" + fieldError.getCode() + ", object:"
+ fieldError.getObjectName() + ", field:"
+ fieldError.getField()+"siamo qui");
model.addAttribute("colloquioRicerca", colloquioRicerca);
return "ColloquioSearchForm";
}//validare datafine minore data inizio
String codiceFiscale = colloquioRicerca.getCodiceFiscale();/*
Date dataColloquio = colloquioRicerca.getDataColloquio();
Date dataIniz = colloquioRicerca.getDataIniz();
Date dataFin = colloquioRicerca.getDataFin();*/
String nome = "%"+colloquioRicerca.getNome()+"%";
String cognome = "%"+colloquioRicerca.getCognome()+"%";
String esitoColloquio = colloquioRicerca.getEsitoColloquio();
Colloquio colloquioTrovato = null;
logger.info("siamo prima dell'if isEmpty");
if (!codiceFiscale.isEmpty()){
logger.info("dentro if is empty");
try{
logger.info("dentro il try:"+colloquioRicerca.getCodiceFiscale());
List<Colloquio> lista = colloquiService.getAllColloquio();
if(lista.isEmpty()){logger.info("lista nulla");}
for(Colloquio colloquio : lista){
logger.info("colloquio su db cf:"+colloquio.getCodiceFiscale());
if(colloquio.getCodiceFiscale().equals(codiceFiscale)){
colloquioTrovato=colloquio;
logger.info("siamo dentro l'if: colloquio trovato"+colloquioTrovato.getCodiceFiscale());
}
}
}
catch(SQLException e){logger.info(e.getMessage()+"siamo qui?");}
}
if (colloquioTrovato == null){
model.addAttribute("colloquioRicerca", colloquioRicerca);
return "ColloquioSearchForm";
}
return "Daje";
}
Below is the error I got in console when jsp processing stops:
/*dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: modelattribute:project.domain.search.ColloquioSearch#5d2ca87b/hereitwritesthecorrectparam
dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: entered
dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: Code:typeMismatch, object:colloquioSearch, field:dataColloquiosiamo qui
dic 21, 2016 9:52:00 AM org.springframework.web.servlet.tags.form.InputTag doStartTag
GRAVE: Neither BindingResult nor plain target object for bean name 'colloquioRicerca' available as request attribute*/
above is the error I got in console since i leave empty the date fields on form; I got the error for DataColloquio, then for DataFin, and then for DataIniz, subsequently. The only way to avoid this error is by filling the form imput fields related
I hope to be into the lines of this site asking for this, thank You all.
P.S.: I know the code is bad structured, and it is not a good way to code the way it is written, I just wanted to explain the issue, meanwhile I am changing the structure, I just do not understand why it is asking me for not leaving empty date fields, and not the others.
It might be better if you print these
Date dataColloquio = colloquioRicerca.getDataColloquio();
Date dataIniz = colloquioRicerca.getDataIniz();
Date dataFin = colloquioRicerca.getDataFin();
directly in your controller, as I kinda doubt that spring will parse the string format coming from your input into Date object without customization.
In short, if you want to bind the Date fields you could register custom data binding for the date via WebDataBinder by simply adds
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
in your controller, with this, even if your input is empty, spring will do the rest for you. You have to notice that the format would be yyyy-MM-dd or just change it if you want. As an alternative, you can also do
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataColloquio;
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataIniz;
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataFin;
And about your error, this probably caused from your service as there's a rs.getTime(..) there, meanwhile the string date from your input cannot be parsed correctly into Date object thus your model object cannot be targetted hence thrown error. As previous my suggestion, try to put #InitBinder annotated method that I give above into your controller and let's hope it solves everything.

how to do binding in Spring annotated request parameter?

i have a controller that is using annotation for request mapping and requestParam.
the controller is working fine. However when submitting a command object with array, spring will crap out saying array index out of bound. i am guessing there is something wrong with binding but don't know how to fix it.
to be more specific, in eclipse i would set debugger at the beginning of the controller, and when submitting the form (by hitting a input submit button) eclipse debugger will not trigger and i will see array index out of bound error in console.
the controller is something like this:
#RequestMapping(value = {"/internal/pcsearch.dex", "/external/pcsearch.dex"},
method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView executeProductCatalogSearch(
HttpServletRequest request,
#RequestParam(value = "cat" ,required = false) String cat,
#RequestParam(value = "brand" ,required = false) String brand,
#ModelAttribute("command") ProductCatalogCommand cmd
){
[edit]
and the jsp is like:
<form name="pForm"
id="pForm"
action="<c:url value="psearch.dex"><c:param name="cat" value="${cat}"/></c:url>"
method="POST"
style="display:inline;">
...
...
<c:forEach var="model" items="${models}" varStatus="modelLinkStatus">
<script>
var modelImg<c:out value="${modelLinkStatus.index}"/>Src = '<c:out value="${model.altModelImage}"/>';
</script>
<spring:bind path="command.models[${modelLinkStatus.index}].modelSkusDisplayed">
<input type="hidden" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" value="<c:out value="${status.value}"/>"/>
</spring:bind>
<spring:bind path="command.updateCartButton">
<input type="submit" value="<spring:message code="orderEntryMessages.ecatalog.button.addToCart" text="Add to Cart" htmlEscape="yes" />" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" class="sub_buttons"/>
</spring:bind>
...
and the command object declare the model array as:
private List<ModelLink> models = new ArrayList<ModelLink>();
where modelLink is a custom ds.
the first foreach tag handle the the model command object and the 2nd part is the submit button i clicked on.
i think you should use AutoPopulatingList as models to bind list to view and controller. for example please refer link. This might resolve your problem of index.

Resources