I'm trying to check if I have a List with items. So I use this code in my HTML
<div class="form-group-petit row">
<div class="col-sm-12">
<table class="table center" id="tableSelectedEstudis">
<col style="width:80%">
<col style="width:20%">
<!--<col style="width:10%">-->
<thead>
<tr>
<th scope="col" data-th-text="#{edicio.estudis}"></th>
<th scope="col" data-th-text="#{edicio.estudis.vigent}">Vigent</th>
<!-- <th scope="col" data-th-text="#{label.accions}">Accions</th> -->
</tr>
</thead>
<tbody>
<tr th:each="estudi : *{listEstudis}" >
<td scope="row" th:text="${estudi.codiEstudi +' - '+ estudi.memo}"/>
<td scope="row" th:text="${estudi.vigentSN}"/>
<!-- <td>
<span class="link" th:attr="data-codiestudi =${estudi.codiEstudi}" id="eliminarEstudi" title="Elimina estudi" th:unless="*{altaOk} OR *{altaKo}"><i class="oi oi-delete"></i></span>
</td> -->
</tr>
<tr></tr>
</tbody>
</table>
</div>
</div>
<label class="error col-sm-10" th:if="${#fields.hasErrors('listEstudis')}" th:errors="*{listEstudis}"></label>
Normally I should add #NonEmpty label in the form and let Spring work automatically. In my case, I can't do it this way and I need to add the error manually. So I do this in my controller:
String[] codes = { "NotEmpty.admEdicionsDetallForm.listEstudis", "NotEmpty.listEstudis",
"NotEmpty.java.util.List", "NotEmpty" };
String objectName = "admEdicionsDetallForm";
Object[] objects = { new DefaultMessageSourceResolvable(
new String[] { "admEdicionsDetallForm.listEstudis", "listEstudis" }, null, "listEstudis") };
if (llistatEstudis.isEmpty()) {
bindingResult.addError(
new ObjectError(objectName, codes, objects, "És obligatori seleccionar almenys un estudi"));
}
But the message is not showing when I try to do it manually, howerver if I do it with the #NonEmpty lable it works.
The rejectValue() method is used to add a validation error to the BindingResult object. https://stackoverflow.com/a/65759773/2039546
So, in your code, instead of:
bindingResult
.addError(new ObjectError(objectName, codes,
objects, "És obligatori seleccionar almenys un estudi"));
Try with:
bindingResult.rejectValue("listEstudis", "error. listEstudis",
"És obligatori seleccionar almenys un estudi!");
Related
This is my controller class read data method. I cant read spring data from requesting. when I do it from postman it works fine but cant read using html page.
#RequestMapping("/index")
public String ItemList(Model model) {
model.addAttribute("itemList", repository.findAll());
return "index";
}
Like this I try to read data using my index.html page
<h2>Medicine List</h2>
<form action="/index" method="POST">
<table>
<thead>
<tr>
<th>ID</th>
<th>MedicineName</th>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>ExDate</th>
</tr>
</thead>
<tbody>
<tr th:each="item:${itemList}">
<td th:text="${item.id}"></td>
<td th:text="${item.MedicineName}"></td>
<td th:text="${item.Description}"></td>
<td th:text="${item.Quantity}"></td>
<td th:text="${item.Price}"></td>
<td th:text="${item.ExDate}"></td>
<td><form action="/delete/item:${itemList}" method="Delete"><input type="submit" value="Delete" /></form></td>
</tr>
</tbody>
</table>
</form>
I have a JSP page that's attached to a list of objects I need to loop through using a JSTL loop. Basically, I want it to display different information about the book and a submit input view (send to another jsp page to see more details about the book).
My question is how can I know which button was clicked and how can I recover the corresponding book.
<table class="table table-striped">
<thead>
<tr>
<th scope="col">N°</th>
<th scope="col">Title</th>
<th scope="col">ISBN</th>
<th scope="col">Author</th>
<th scope="col">Year</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"></th>
<c:set var="count" value="${1}" scope="request"/>
<c:forEach items= "${requestScope.booksList}" var="b">
<tr>
<td>${count }</td>
<td> ${b.getTitle() } </td>
<td> ${b.getISBN() } </td>
<td> ${b.getAuthor() } </td>
<td> ${b.getYear() } </td>
<td><input type="submit" value="View" name="View${count }"></td>
<td><input type="submit" value="Mark" name="Mark"></td>
</tr>
<c:set var="count" value="${count + 1}" scope="request" />
</c:forEach>
</tr>
</tbody>
</table>
my requirement is based on group of checkbox checks shipping address fields will be disable or enabled.
make clear my requirement:Wicket id:"nonDigital" having 6 check boxes.if any one of check box is checked then only shipping address section is enabled and then only user can enter value.
Here is my code
My HTML code:
<fieldset class="deliveryFormats">
<h2 class="sectionHeading">Delivery Formats</h2>
<span class="required">* Required Field</span>
<br/>
<div class="leftDiv">
<label>Non-digital</label>
<div class="radioLabel" wicket:id="nonDigital" >
<label>
<input class="checkbox" type="checkbox" name="formatType" />Beta SP NTSC
</label>
</div><!-- /.radioLabel non digital -->
</fieldset>
<fieldset class="shippingAddress" style="border-bottom: 0px;" >
<h2 class="sectionHeading">Shipping Address</h2>
<table class="form">
<tbody>
<tr>
<th class="fieldName" scope="row">Company</th>
<td class="fieldEdit">
<input class="organization" type="text" wicket:id="address.organization"/>
</td>
</tr>
<tr>
<th class="fieldName" scope="row">Address 1</th>
<td class="fieldEdit">
<input class="long" type="text" wicket:id="address.line1">
</td>
</tr>
<tr>
<th class="fieldName" scope="row">Address 2</th>
<td class="fieldEdit">
<input class=" long" type="text" wicket:id="address.line2">
</td>
</tr>
<tr>
<th class="fieldName" scope="row">Address 3</th>
<td class="fieldEdit">
<input class="long" type="text" wicket:id="address.line3">
</td>
</tr>
<tr>
<th class="fieldName" scope="row">City</th>
<td class="fieldEdit">
<input class="long" type="text" wicket:id="address.city"/>
</td>
</tr>
<tr>
<th class="fieldName" scope="row">State</th>
<td class="fieldEdit">
<input class="long" type="text" wicket:id="address.state"/>
</td>
</tr>
<tr>
<th class="fieldName" scope="row">Postal Code</th>
<td class="fieldEdit">
<input class="postalcode" type="text" wicket:id="address.postalCode"/>
</td>
</tr>
</tbody>
</table>
Java code:
List<DeliveryFormat> formatChoices = lookupProcessor.getLookupValues(DeliveryFormat.class);
List<DeliveryFormat> nonDigital = new ArrayList<DeliveryFormat>();
List<DeliveryFormat> digital = new ArrayList<DeliveryFormat>();
Iterator<DeliveryFormat> nondigitalIterator = formatChoices.iterator();
while(nondigitalIterator.hasNext()){
DeliveryFormat df = nondigitalIterator.next();
if(df.getLabel().equals("Audio Bundle") || df.getLabel().equals("XDCAM file")|| df.getLabel().equals("FTP")){
digital.add(df);
}
else
{
nonDigital.add(df);
}
}
//Add the check boxes for Delivery format for digital List
// add(new CheckBoxMultipleChoice<DeliveryFormat>("nonDigital", nonDigital, new ChoiceRenderer<DeliveryFormat>("label")));
ChoiceRenderer<DeliveryFormat> deliveryFormatShippment = new ChoiceRenderer<DeliveryFormat>("label", "id");
CheckBoxMultipleChoice<DeliveryFormat> nonDigitalDelivery = new CheckBoxMultipleChoice<DeliveryFormat>(
"nonDigital", nonDigital, deliveryFormatShippment);
CheckBoxMultipleChoice<DeliveryFormat> digitalDelivery = new CheckBoxMultipleChoice<DeliveryFormat>(
"digital", digital, deliveryFormatShippment);
add(nonDigitalDelivery);
/*final CheckBox test = new CheckBox("nonDigital");
test.setOutputMarkupId(true);
nonDigitalDelivery.add(new AjaxEventBehavior("onKeyUp")
{
*//**
*
*//*
private static final long serialVersionUID = 1L;
#Override
protected void onEvent(AjaxRequestTarget target) {
// TODO Auto-generated method stub
test.setEnabled(false);
target.addComponent(test);
}
});*/
You should try to enable the markupid to be written:
textArea.setOutputMarkupId(true);
and then add this component to the target:
textArea.setEnabled(false):
target.add(textArea);
I am having trouble with my .jsp code in Spring MVC where I am using a date picker. When I access the date time picker, the code works fine. But in case i try to leave that field empty, i.e not use the date picker, it takes null as default( which it should) and then gives the error :
Failed to convert property value of type java.lang.String to required type java.util.Date for property ticComDropoofDate; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type java.lang.String to type java.util.Date; nested exception is java.lang.IllegalArgumentException
I am attaching my code with this and any help will be appreciated.
My controller:
public class TicketController extends MasterController{
#InitBinder
protected void initBinder(WebDataBinder binder){
if(binder.getTarget() instanceof TicketDetailsBean)
binder.setValidator(new TicketDetailsValidator());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
#RequestMapping(value="/TicketRegistration", method=RequestMethod.POST)
public ModelAndView createTicketRegistration(#Valid TicketDetailsBean ticket, BindingResult result, Model model) throws SQLException{
TicketManager dm = new TicketManager();
TechManager dm1 = new TechManager();
SimpleMailManager sm = new SimpleMailManager();
ModelAndView modelAndView = new ModelAndView();
if(!result.hasErrors()){
try{
String message = dm.saveTicketRegistration(ticket);
/*if(check)
{
TicketDetailsBean ticket1 = new TicketDetailsBean();
OwnerDetailsBean owner1 = new OwnerDetailsBean();
ticket1 = sm.fetchData(ticket);
owner1 = sm.fetchOwner(ticket1);
}*/
sm.sendMail();/*(owner1,ticket1);*/
List<TicketDetailsBean> ticket2 = dm.findRegisteredTicket();
if(message != null){
message = "Duplicate entry not allowed. Data with same name already in the database...";
modelAndView.addObject("Message", message);
}
modelAndView.setViewName("TicketDatabase");
modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
modelAndView.addObject("ticketList", ticket2);
modelAndView.addObject("techDetailsBean", new TechDetailsBean());
modelAndView.addObject("tech", globalBean);
return modelAndView;
}catch (Exception e) {
e.printStackTrace();
}
}
else{
List<TechDetailsBean> tech = dm1.findRegisteredTech();
modelAndView.addObject(result.getAllErrors());
modelAndView.setViewName("TicketRegistration");
modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
modelAndView.addObject("techDetailsBean", new TechDetailsBean());
modelAndView.addObject("tech", globalBean);
modelAndView.addObject("techList",tech);
return modelAndView;
}
/*List<TicketDetailsBean> ticket2 = dm.findRegisteredTicket();
modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
modelAndView.addObject("ticketList", ticket2);*/
return modelAndView;
}
My jsp :
<script>
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: 'yy-mm-dd',
showOn: "button",
buttonImage: "<%=request.getContextPath() %>/resources/images/calendar.gif",
buttonImageOnly: true
});
}).val('');
$(function() {
$( "#datepicker1" ).datepicker({ dateFormat: 'yy-mm-dd',
showOn: "button",
buttonImage: "<%=request.getContextPath() %>/resources/images/calendar.gif",
buttonImageOnly: true
});
}).val('');
</script>
<form:form modelAttribute="ticketDetailsBean" action="TicketRegistration" method="post">
<table>
<tr>
<td>
<h1>Ticket Registration Form</h1>
<h3>Please enter the information below</h3>
<h3>click "<b>Save</b>" when complete. </h3>
<h3> Fields marked with an asterisk '<b>*</b>' are required.</h3>
<h3> Click "<b>Reset</b>" to clear the fields</h3>
</td>
</tr>
<tr>
<td>
<fieldset title="info">
<legend><b>Ticket Information</b></legend>
<table>
<tr>
<td align="left"><form:label for="ticDate" path="ticDate" cssErrorClass="error">* Ticket Date :</form:label></td>
<td align="left"><form:input path="ticDate" id="datepicker1" size="35" maxlength="35"/> <form:errors path="ticDate" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticServicetag" path="ticServicetag" cssErrorClass="error">* Service Tag Number :</form:label></td>
<td align="left"><form:input name="ticServicetag" path="ticServicetag" id="ticSrvctag" size="35" maxlength="35" value = "${computerList.comServicetag}" /> <form:errors path="ticServicetag" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticOwnerSuUsername" path="ticOwnerSuUsername" cssErrorClass="error">* Owner Su_username :</form:label></td>
<td align="left"><form:input path="ticOwnerSuUsername" id="owsusenm" size="35" maxlength="35" value ="${computerList.comOwnerSUUsername }" /> <form:errors path="ticOwnerSuUsername" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticTechname" path="ticTechname" cssErrorClass="error">* Tech Name :</form:label></td>
<td align="left">
<select name="ticTechname" id = "ticTechname" id="slectboxid1">
<option value = ""> ---Select--- </option>
<c:forEach var="item" items="${techList}">
<option value = "${item.techName}"><c:out value= "${item.techName}"/></option>
</c:forEach>
</select>
<form:errors path="ticTechname" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticComProblem" path="ticComProblem" cssErrorClass="error">* Problem :</form:label></td>
<td align="left"><form:textarea path="ticComProblem" rows ="3" cols ="27"/> <form:errors path="ticComProblem" cssErrorClass="error" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticComments" path="ticComments" cssErrorClass="error"> Comments :</form:label></td>
<td align="left"><form:textarea path="ticComments" rows = "3" cols = "27"/> <form:errors path="ticComments" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticItemtoOrder" path="ticItemtoOrder" cssErrorClass="error"> Item To Order :</form:label></td>
<td align="left"><form:input path="ticItemtoOrder" size="35" maxlength="35" /> <form:errors path="ticItemtoOrder" /></td>
</tr>
<tr>
<td align="left"><form:label for="ticComDropoofDate" path="ticComDropoofDate" cssErrorClass="error"> Computer Drop Off Date:</form:label></td>
<td align="left"><form:input path="ticComDropoofDate" id="datepicker" size="35" maxlength="35" /> <form:errors path="ticComDropoofDate"/></td>
</tr>
<tr>
<td align="left"><form:label for="ticAssignedTech" path="ticAssignedTech" cssErrorClass="error">* Tech Assigned :</form:label></td>
<td align="left">
<select name="ticAssignedTech" id = "ticAssignedTech" id="slectboxid2">
<option value = ""> ---Select--- </option>
<c:forEach var="item" items="${techList}">
<option value = "${item.techName}"><c:out value= "${item.techName}"/></option>
</c:forEach>
</select>
<form:errors path="ticAssignedTech" />
</td>
</tr>
<tr>
<td align="left"><form:label for="ticStatus" path="ticStatus" cssErrorClass="error">* Ticket Status :</form:label></td>
<td align="left">
<select name="ticStatus" id = "ticStatus" id="slectboxid3">
<option value="">---Select--- </option>
<option value="Open"> Open </option>
<option value="InProgress">In Progress</option>
<option value="Closed">Closed</option>
</select>
<form:errors path="ticStatus" />
</td>
</tr>
<tr>
<td align="left"><form:label for="ticAddEquipments" path="ticAddEquipments" cssErrorClass="error"> Additional Equipments dropped with Computer :</form:label></td>
<td align="left"><form:textarea rows= "3" path="ticAddEquipments" cols ="27"/> <form:errors path="ticAddEquipments" /></td>
</tr>
</table>
</fieldset>
<fieldset>
<div align="center">
<form action="TicketDatabase" method="get">
<input type="submit" name="submit" value="Save"/>
<input type="reset" name="reset"/>
</form>
</div>
</fieldset>
</td>
</tr>
</table>
The exception message:
Unable to convert value "" from type java.lang.String to type java.util.Date
spring throws because you have not informed spring to convert empty string to null.
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
pass true if you want null when empty string like:
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
Spring CustomDateEditor constructor java docs has:
public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty)
Create a new CustomDateEditor instance, using the given DateFormat for parsing and
rendering. The allowEmpty parameter states if an empty String should
be allowed for parsing, i.e. get interpreted as null value. Otherwise,
an IllegalArgumentException gets thrown in that case.
Parameters:
dateFormat - DateFormat to use for parsing and rendering
allowEmpty - if empty strings should be allowed
Question is i have table in which i want to populate the values of file name and file size after user click the choose file button and select any number of files, Now the issue is if the user click choose files button second time i want to append the new values in the table and add the new file in the array so that it can uploaded.. my code is,
html form code:
<form id="simpleuploadform" method="post" action="upload" enctype="multipart/form-data">
<table class="span10" border="0">
<tr>
<td colspan="3">
<legend>Simple Upload</legend>
</td>
</tr>
<tr>
<td>
<input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
<div id="successdiv" hidden="true" class="label label-success">Image uploaded successfully</div>
<div id="errordiv" hidden="true" class="label label-error">Image not successfully uploaded</div>
<div id="streamdiv" hidden="true" class="label label-warning">Issue while uploading try again</div>
</td>
<td id="renameFile" align="right"></td>
<td id="removeFile" align="right"></td>
</tr>
<tr>
<td colspan="3">
<div id="uploaddiv">
<table id="uploadTable" class="table table-striped table-bordered" width="200" height="200" scrolling="yes">
<thead>
<tr>
<th>Title</th>
<th>Size</th>
</tr>
</thead>
<tbody id="tbodyid">
<tr id="tr0">
<td id="filetd0" height="10px" width="50px"></td>
<td id="filesizetd0" height="10px" width="5px"></td>
</tr>
<tr id="tr1">
<td id="filetd1" height="10px" width="50px"></td>
<td id="filesizetd1" height="10px" width="5px"></td>
</tr>
<tr id="tr2">
<td id="filetd2" height="10px" width="50px"></td>
<td id="filesizetd2" height="10px" width="5px"></td>
</tr>
<tr id="tr3">
<td id="filetd3" height="10px" width="50px"></td>
<td id="filesizetd3" height="10px" width="5px"></td>
</tr>
<tr id="tr4">
<td id="filetd4" height="10px" width="50px"></td>
<td id="filesizetd4" height="10px" width="5px"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td id="filecount" height="10px" width="50px"></td>
<td id="totalsize" height="10px" width="5px"></td>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="btn btn-primary" onClick="CloseAndRefresh();" value="Start Upload" id="startButton" disabled>
<input type="reset" class="btn btn-primary" onClick="Clear();" value="Clear" id="clearButton" disabled>
<input type="button" class="btn" onClick="window.close();" value="Close">
</td>
</tr>
</table>
javascript code:
<script type="text/javascript">
var totalsizeOfUploadFiles = 0;
function getFileSizeandName(input)
{
var select = $('#uploadTable tbody');
$('#renameFile').empty();$('#removeFile').empty();
if(input.files.length > 0)
{
$('#renameFile').append($('<a id="renameRec">Rename Selected</a>'));
$('#removeFile').append($('<a id="removeRec">Remove Selected</a>'));
$('#startButton').removeAttr("disabled", "disabled");
$('#clearButton').removeAttr("disabled", "disabled");
}
//if(input.files.length <= 5)
//{
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size;
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
var filename = input.files[i].name;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
if(i<=4)
{
$('#filetd'+i+'').text(filename);
$('#filesizetd'+i+'').text(filesizeInMB);
}
else if(i>4)
select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles += parseFloat(filesizeInMB);
$('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
if(i==0)
$('#filecount').text("1file");
else
{
var no = parseInt(i) + 1;
$('#filecount').text(no+"files");
}
}
//}
}
function CloseAndRefresh()
{
var daa = '<%=status%>';
if(daa == "true")
$('#successdiv').show();
else if(daa == "false")
$('#errordiv').show();
else
$('#streamdiv').show();
opener.location.reload(true);
self.close();
}
function Clear()
{
$('#uploadTable tbody tr td').each(function(){
$(this).text("");
});
$('#uploadTable tfoot tr td').each(function(){
$(this).text("");
});
}
i am trying to do as like this http://www.shutterfly.com/ image upload.
any help will be appreciated, thank you friends...
You are navigating away using javascript, function CloseAndRefresh on clicking submit button.
What actually happens is that the uploading request is being submitted while the CloseAndRefresh function is being executed at almost the same time using different thread. If the upload request is not fast enough, the web page will get refresh first and your upload request get terminated immediately. There is no easy way to prevent this using your existing code.
You should use advanced method of uploading like jQuery uploading plugin to send the request. The plugin provide an binder to execute function on successful/failed submittsion.
Thank you gigadot, i solve the issue as like below,
The html form have the same code as i posted earlier, in the previous js code i have the CloseAndRefresh() method i remove it now from js as well as from the submit button onclick event.
When the form action called the controller, in which i have the code
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String UploadReceipts(#RequestParam("files[]") List<MultipartFile> file, Model model) throws IOException {
boolean status = false;
try
{
for(int i=0; i< file.size(); i++)
{
if(!file.get(i).isEmpty())
{
CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
status = simpleUploadService.uploadFileandSave(cm);
model.addAttribute("status", status);
}
}
}
catch (IOException e) {
status = false;
model.addAttribute("status", status);
}
return "pages/simpleUploadStatus";
}
Now i redirect it to another page in which i throws the appropriate messages for the user.
that's all...