Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.List.get(int)" is null when handling a form - spring

I have a form where I have to display a checkbox for each step and an input to choose the position of the step.
So, I would like to add each checked step in the database, with the input also retrieved.
Here is my form:
<th:block th:each="etape: ${etapes}">
<input class="form-label mt-4" type="checkbox" name="etapes" th:field="*{etapes}" th:value="${etape.id}"/>
<label th:text="${etape.poste.name}"></label>
<input class="form-label mt-4" type="number" name="positionsPoste" th:field="*{positionsPoste}" th:placeholder="#{new.cheminementEtape.positionPoste.label}"
/>
<br>
</th:block>
and my service:
List<CheminementEtape> cheminementEtapes = new ArrayList<>();
for(int i=0; i<cheminementForm.getEtapes().size(); i++) {
for(int y=0; y<cheminementForm.getPositionsPoste().size(); y++){
CheminementEtape cheminementEtape = CheminementEtape.builder().disable(false).etape(cheminementForm.getEtapes().get(i)).cheminement(cheminement).positionPoste(cheminementForm.getPositionsPoste().get(y)).build();
cheminementEtapes.add(cheminementEtape);
}
}
this.cheminementEtapeService.add(cheminementEtapes);
return cheminement;
and my form:
#Data
public class CheminementForm {
#NotNull(message = "{cheminement.form.name.notEmpty}")
#Size(min=2, max=30)
private String name;
#NotNull(message = "{cheminementEtape.form.etape.notEmpty}")
private List<Etape> etapes;
#NotNull(message = "{cheminementEtape.form.positionPoste.notEmpty}")
private List<Integer> positionsPoste;
}
So I make two for loops, and for each checked step, I get the position input and I add it in the database with the retrieved values.
However, when I do this, I get an error:
Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.List.get(int)" is null
at line 60
I don't understand... Any ideas ? thanks in advance

Related

Spring Boot dropdown menu with options select validation

I have ENUM where I saved types of Income Categories, than I use that ENUM and map it inside my Entity, later I populate my dropdown list with that ENUM and show to user. I want to create a validation so user cant submit form until he choose one option from the dropdown list. Below is code that I think is useful to solve this and also the way I tried to show a error to the user if he didn't select any option from dropdown menu.
I have this ENUM:
public enum IncomeCategories {
SALARY("Salary"),
BUSINESS("Business"),
GIFTS("Gifts"),
EXTRA_INCOME("Extra income"),
LOAN("Loan"),
PARENTAL_LEAVE("Parental Leave"),
INSURANCE_PAYOUT("Insurance payout"),
OTHER("Other");
private final String displayName;
IncomeCategories(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This is ENUM inside entity:
#Enumerated(EnumType.STRING)
#NotNull(message = "Please, select option from list.")
#Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;
And this is how I tried to show error if nothing is selected from dropdown menu:
<div class="form-group col-md-8">
<select th:field="${transaction.incomeCategories}">
<option value="0">Select income category</option>
<option
th:each="incomeCategories : ${incomeCategories}"
th:value="${incomeCategories}"
th:text="${incomeCategories.displayName}"
></option>
</select>
<span
th:if="${#fields.hasErrors('${transaction.incomeCategories}')}" th:errors="${transaction.incomeCategories}"
class="text-danger"></span>
</div>
But I'm getting this:

Connecting Telerik Blazor Control to Entity and Ardalis.SmartEnum

Using SmartEnum's https://github.com/ardalis/smartenum to handle Entity Framework 5.0 fields for things such as State, Country, Etc.
public sealed class StatesEnum : SmartEnum<StatesEnum>
{
public static readonly StatesEnum NotSpecified = new StatesEnum("(Select One)", 0);
public static readonly StatesEnum Alabama = new StatesEnum("Alabama", 1);
public static readonly StatesEnum Alaska = new StatesEnum("Alaska", 2);
public static readonly StatesEnum Arizona = new StatesEnum("Arizona", 3);
public static readonly StatesEnum Arkansas = new StatesEnum("Arkansas", 4);
public static readonly StatesEnum California = new StatesEnum("California", 5);
...
}
I am creating a Blazor Component for creating a job posting in our company's job board that uses these SmartEnum field types as one of the values in the entity. In the component I am using Telerik's Blazor DropDownList https://docs.telerik.com/blazor-ui/components/dropdownlist/overview to handle the fields that use these SmartEnum values. I have it correctly displaying the enum text and values using this code:
<TelerikDropDownList Id="dropStates" Data="#StatesEnum.List" TextField="#nameof(StatesEnum.Name)" ValueField="#nameof(StatesEnum.Value)" #bind-Value="#JobPostingVM.StateId"></TelerikDropDownList>
I am attempting to directly connect my View Model class (JobPostingVM) to the drop down list instead of creating a separate property for the selected value but I run into issues with the code complaining that you cant cast a SmartEnum to a type of int. Looking for a elegant solution outside of setting a property to store each selected value in this long form.
I am a Support Engineer with Telerik on the UI for Blazor team. I did some testing with the described scenario and found that it will require using a value external to the model.
For example, use a selectedValue variable as shown in the Bind to a Model documentation. The selectedValue variable can be set in the OnInitializedAsync method. Let me provide an example of this below.
Example
In the example, I am using a person model that is bound to a form with a SmartEnum for the SelectedState property. I am also setting default values in the model so that it displays the binding on page load. Let's go over each below.
Person Model
The person class is a basic CLR object with default values set for the collection properties.
public class Person
{
// Added for test
[Required(ErrorMessage = "Select a state")]
public StatesEnum SelectedState { get; set; } = StatesEnum.Alabama; // Default Value
// Original properties
[Required(ErrorMessage = "Enter your first name")]
[StringLength(10, ErrorMessage = "That name is too long")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Enter your last name")]
[StringLength(15, ErrorMessage = "That name is too long")]
public string LastName { get; set; }
[Required(ErrorMessage = "An email is required")]
[EmailAddress(ErrorMessage = "Please provide a valid email address.")]
public string Email { get; set; }
public int? Gender { get; set; } = 4; // Default Value
[Required]
[Range(typeof(DateTime), "1/1/2020", "1/12/2030", ErrorMessage = "Value for {0} must be between {1:dd MMM yyyy} and {2:dd MMM yyyy}")]
public DateTime StartDate { get; set; }
[Required(ErrorMessage = "Choose the team and technology you want to work on")]
public string PreferredTeam { get; set; } = "Blazor"; // Default Value
}
The SelectedState SmartEnum
The selected state is a property dervid from the SmartEnum implementation.
public sealed class StatesEnum : SmartEnum<StatesEnum>
{
private StatesEnum(string name, int value) : base(name, value)
{
}
public static readonly StatesEnum NotSpecified = new StatesEnum("(Select One)", 0);
public static readonly StatesEnum Alabama = new StatesEnum("Alabama", 1);
public static readonly StatesEnum Alaska = new StatesEnum("Alaska", 2);
public static readonly StatesEnum Arizona = new StatesEnum("Arizona", 3);
public static readonly StatesEnum Arkansas = new StatesEnum("Arkansas", 4);
public static readonly StatesEnum California = new StatesEnum("California", 5);
}
Blazor Component
The custom form comonent then uses the OnInitializedAsync method to populate the model and set the selected value.
#page "/"
#using TBACS.DropDownListSmartEnumBinding.Models
<div class="container-fluid">
<div class='row my-4'>
<div class='col-12 col-lg-9 border-right'>
<div class="row example-wrapper">
<div class="col-xs-12 col-sm-6 offset-sm-3 example-col card p-4">
<EditForm Model="#person" OnValidSubmit="#HandleValidSubmit" class="k-form">
<DataAnnotationsValidator />
<fieldset>
<legend>User Details</legend>
<div class="form-group">
<label for="StatesDDL">
<span>Select State <span class="k-required">*</span></span>
</label>
<TelerikDropDownList Data="#StatesEnum.List"
#bind-Value="#selectedValue"
TextField="#nameof(StatesEnum.Name)"
ValueField="#nameof(StatesEnum.Value)"
Id="StatesDDL"
Width="100%">
</TelerikDropDownList>
</div>
<div class="form-group">
<label for="FNameTb">
<span>First Name <span class="k-required">*</span></span>
</label>
<TelerikTextBox #bind-Value="#person.FirstName" Width="100%" Id="FNameTb" />
</div>
<div class="form-group">
<label for="LNameTb">
<span>Last Name <span class="k-required">*</span></span>
</label>
<TelerikTextBox #bind-Value="#person.LastName" Width="100%" Id="LNameTb" />
</div>
<div class="form-group">
<label for="GenderDDL">
<span>Gender <span class="k-field-info">optional</span></span>
</label>
<TelerikDropDownList #bind-Value="#person.Gender" DefaultText="Select gender"
Data="#genders" TextField="Text" ValueField="Id"
Width="100%" PopupHeight="auto" Id="GenderDDL">
</TelerikDropDownList>
</div>
<div class="form-group">
<label for="EmailTb">
<span>Email <span class="k-required">*</span></span>
</label>
<TelerikTextBox #bind-Value="#person.Email" Width="100%" Id="EmailTb" />
</div>
</fieldset>
<fieldset>
<legend>Team Preferences</legend>
<div class="form-group">
<label for="StartDateDP">
<span>Start date <span class="k-required">*</span></span>
</label>
<TelerikDatePicker #bind-Value="#person.StartDate" Width="100%" Id="StartDateDP" />
</div>
<div class="form-group">
<label for="TeamDDL">
<span>Preferred Team <span class="k-required">*</span></span>
</label>
<TelerikDropDownList #bind-Value="#person.PreferredTeam"
DefaultText="Preferred team" Id="TeamDDL"
Data="#Teams" Width="100%">
</TelerikDropDownList>
</div>
</fieldset>
<ValidationSummary />
#if (ShowSuccessMessage)
{
<div class="alert alert-info">
Application form submitted Successfully, we will get back to you
</div>
}
<div class="text-right">
<TelerikButton ButtonType="#ButtonType.Button" OnClick="#CancelForm">Cancel</TelerikButton>
<TelerikButton ButtonType="#ButtonType.Submit" Primary="true">Submit</TelerikButton>
</div>
</EditForm>
</div>
</div>
</div>
</div>
</div>
#code{
Person person { get; set; }
bool ShowSuccessMessage { get; set; }
protected override Task OnInitializedAsync()
{
// Bind model on load
GetDefaultPerson();
return base.OnInitializedAsync();
}
async void HandleValidSubmit()
{
// implement actual data storage here
ShowSuccessMessage = true;
await Task.Delay(2000);
ShowSuccessMessage = false;
GetDefaultPerson();
StateHasChanged();
}
void CancelForm()
{
GetDefaultPerson();
}
// External selected value primitive
int selectedValue { get; set; } = 0;
void GetDefaultPerson()
{
// in reality you may be pulling data from a service or authentication logic
// not only for the form model, but also for the data sources below
person = new Person()
{
StartDate = DateTime.Now.AddDays(7)
};
// Get the selected value from the model.
selectedValue = person.SelectedState.Value;
}
IEnumerable<DropDownModel> genders = new List<DropDownModel>
{
new DropDownModel {Text = "female", Id = 1},
new DropDownModel {Text = "male", Id = 2},
new DropDownModel {Text = "other", Id = 3},
new DropDownModel {Text = "I'd rather not say", Id = 4}
};
List<string> Teams = new List<string>
{
"Blazor", "Python", "Ruby", "Java", "JavaScript", "Assembler"
};
}
Misc. Models
The other models for the example are built around the DropDown.
Menu Item
public class MenuItem
{
public string Text { get; set; }
public string Url { get; set; }
public List<MenuItem> Items { get; set; }
}
DropDownModel
public class DropDownModel
{
public int? Id { get; set; }
public string Text { get; set; }
}
Wrapping Up
I believe the example answers the question. From what I understand, it seems like the result is what you were hoping to avoid, unfortunately. Let me know if you have any additional questions.
I hope this helps! Thank you for developing with UI for Blazor.
Eric D. Rohler

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.

Format LocalDateTime with spring, jackson

In a spring rest application, i send a objet who contain a date
{ appointmentId: "", appointmentTypeId: "1", appointmentDate:
"2015-12-08T08:00:00-05:00" }
In my dto side
for my appointmentDate i have
#DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME)
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime appointmentDate;
In my dependencies i have
jackson-datatype-jsr310-2.6.3
I get this error
rg.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Text '2015-12-08T13:00:00.000Z' could not be
parsed, unparsed text found at index 23 (through reference chain:
server.dto.AppointmentDto["appointmentDate"]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Text
'2015-12-08T13:00:00.000Z' could not be parsed, unparsed text found at
index 23 (through reference chain:
server.dto.AppointmentDto["appointmentDate"])
tried only with DateTimeFormat, only with JsonDeserialize and both, but get the same error.
Edit
#RequestMapping(value = "/rest")
#RestController
public class LodgerController {
#RequestMapping(value = "/lodgers/{lodgerId}/appointments", method = RequestMethod.POST)
public Long createAppointmentsByLodgerId(#PathVariable("lodgerId") Long lodgerId, #RequestBody AppointmentDto appointmentDto) {
return appointmentService.save(appointmentDto);
}
}
public class AppointmentDto {
private Long appointmentId;
private Long appointmentTypeId;
private Long lodgerId;
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime appointmentDate;
public AppointmentDto() {
}
}
<form id="lodgerAppointmentForm" class="form-horizontal" role="form">
<input type="hidden" id="lodgerId" name="lodgerId">
<input type="hidden" id="lodgerAppointmentId" name="appointmentId">
<div class="form-group">
<label for="lodgerAppointmentDate" class="col-sm-2 control-label">Date</label>
<div class="col-sm-10">
<div class="input-group date" id="appointmentDatepicker" >
<input type="text" class="form-control" id="lodgerAppointmentDate" name="appointmentDate">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar">
</span>
</span>
</div>
</div>
</div>
</form>
var locale = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage);
moment().locale(locale);
$('#appointmentDatepicker').datetimepicker({
format: 'DD/MM/YYYY H:mm',
allowInputToggle: true
});
var lodgerId = $('#lodgerId').val();
var type = "post";
var url = "http://localhost:8080/rest/lodgers/" + lodgerId + "/appointments";
var data = transForm.serialize('#lodgerAppointmentForm');
data.appointmentDate = $('#appointmentDatepicker').data('DateTimePicker').date().format();
data.lodgerId = lodgerId;
data = JSON.stringify(data);
jQuery.ajax({
type: type,
url: url,
contentType: "application/json",
data: data,
success: function (data, status, jqXHR) {
},
error: function (jqXHR, status) {
}
});
transform.js come from https://github.com/A1rPun/transForm.js/blob/master/src/transForm.js
bootstrap datetimepicker come from https://github.com/Eonasdan/bootstrap-datetimepicker
Moment use 2015-12-09T08:00:00-05:00 (ISO 8601)
DateTimeFormatter.ISO_LOCAL_DATE_TIME who is: 2015-12-09T08:00:00 (ISO 8601)
both don't seem to use the same format
I think that your problem is described here:
https://github.com/FasterXML/jackson-datatype-jsr310/issues/14
I encounter the same error when was playing around with LocalDateTime and REST API. The problem is that you can serialize LocalDateTime to something like this:
2015-12-27T16:59:29.959
And you can create valid Date object in JavaScript from that string.
On the other hand if you try to POST/PUT JavaScript date to server then this:
var myDate = new Date();
JSON.stringify(myDate);
will create string like this (with extra Z - which stands for zulu time/UTC time zone):
2015-12-27T16:59:29.959Z
And that extra time zone info causes error in your case during deserialization because LocalDateTime don`t have time zone.
You can try to use ZonedDateTime on ther server or format by yourself date string on client side before sending (without Z suffiks).

Send values get from append forms to spring controller

I was creating a model where the structure as follows:
public class A {
private Long id;
private Type type;
private Set<String> names;
private Set<Long> ids;
private Set<String> subnames;
private Set<Long> subids;
...........
}
I would like to create the model, with multiple fields as many as I like.
so the I have created the form as follows to add new rows dynamically.
Creation Form: One of the fields-->
<form>
<div id="addNewname" class="form-group">
<label>name</label>
<div class="col-lg-4">
<input type="text" name="name_1" id="name" readonly>
</div>
<button id="btnAddname" type="button"
type="hidden"
value="btnAddName" name="btnAddName">Add
New</button>
</div></form>
With the Script to add new as follows:
int count = 1;
$(document).on("click", "#btnAddNew", function(){
count++;
$('#addNewNew').after(
'<div>' +
'<label> New Name</label>'+
'<div >' +
'<select name="name_'+ count +'">'+
'<option value="0">None</option>' +
'<c:forEach items="${names}" var="name">' +
'<option value="${name.id}">${name.name}</option> '+
'</c:forEach>'+
'</select>'+
'</div>'+
'</div>');
});
I was able to send the value to the controller of the value name="name_1" where the form been defined, but I could not do the same for the values created from the append form--script.
Any idea or suggestion to work out this, I have tried many methods but ...
You may use LazyList to add as many names you want.
In your command class, instead of using Set to define your names, try this,
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;
...
private List names = LazyList.decorate( new ArrayList(),
FactoryUtils.instantiateFactory(String.class));
...
In the Jsp page, all that are needed is using the arrayIndex to access or bind values. i.e.
<form:input path="names[0]" cssErrorClass="errorInput" maxlength="30"/>
In the javascript, do the same, use the arrayIndex when your create more text input on the fly.

Resources