Not accessing the date picker gives the conversion error - java

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

Related

Parameter request not returning actual value

I have a table that does not live in a form, but I want the button in each row to correlate and to delete the contact from that table row when it's clicked. I could do an ajax call but I was hoping to just handle it through a spring boot controller method. This is how I set it up.
#RequestMapping(value="/removeContact")
public String removeContact(final CarrierAppointment carrierAppointment, final HttpServletRequest req, Model model){
final Integer rowId = Integer.valueOf(req.getParameter("trashContact"));
carrierAppointment.getContactList().remove(rowId.intValue());
model.addAttribute("carrierAppointment", carrierAppointment);
return "redirect:/carrierAppointment/details/"+carrierAppointment.getId();
}
<table class="table table-striped" data-classes="table-no-bordered" data-striped="true" data-show-columns="true" >
<thead>
<tr>
<th>Contact Type</th>
<th>Contact Name</th>
<th>Contact's Email</th>
<th>Contact's Phone</th>
<th></th>
<th th:if="${role.isCarrierAdmin}" class="text-right"><a class="trigger-add-contact btn btn-default" id="addCommercialContact" name="addCommercialContact"><span class="fa fa-plus"></span></a></th>
</tr>
</thead>
<tbody>
<tr th:each="contact,stat : *{carrier.contactList}" th:if="*{carrier.contactList[__${stat.index}__].contactTable}=='Commercial Lines'">
<td>
<select class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactType}">
<option value="Account Manager">Account Manager</option>
<option value="Marketing Manager">Marketing Manager</option>
<option value="Underwriter">Underwriter</option>
</select>
</td>
<td> <input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactName}"/></td>
<td> <input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactEmail}"/></td>
<td><input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactPhone}"/></td>
<td> <input type="hidden" value='Commercial Lines' th:field="*{carrier.contactList[__${stat.index}__].contactTable}"/></td>
<td class="text-right" th:if="${role.isCarrierAdmin}"> <button type="button" name="trashContact" th:value="${stat.index}" th:onclick="'window.location.href=\'/removeContact\''" class="btn btn-danger "><span class="fa fa-trash"></span></button></td>
</tr>
</tbody>
</table>
The line of code that is requesting the parameter and getting the value is where my code is getting hung up. It is returning null instead of a value. Any idea how to adjust this line of code so it actually gets the value that exists?
Maybe the way I have the onclick set up, it's not actually sending the row value through to the controller method?
This is exactly where in the code it is getting hung up:
public String getParameter(String name) {
this.handleQueryParameters();
ArrayList<String> values = (ArrayList)this.paramHashValues.get(name);
if (values != null) {
return values.size() == 0 ? "" : (String)values.get(0);
} else {
return null;
}
}

Getting selected option value from controller in Spring MVC

I'm making a Spring MVC project, and I have this form in my .jsp
JSP
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
So I have User and CafeTable models, but my model attribute is CafeTable.
With the submit button I need to get both selected values in my controller:
#RequestMapping(value = "/admin/assign/add", params = "assign", method = RequestMethod.POST)
public String assign(#ModelAttribute("cafeTable") CafeTable cafeTable) {
//set cafeTable's UserID field matching selected fullName value
tableService.addTable(cafeTable);
return "admin";
}
How can I do this?
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<input type="hidden" value="${user.fullName}" name="fullname">
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
If you don't have fullname property in CafeTable try to add a hidden field inside form:form like
<input type="hidden" value="${user.fullName}" name="fullname">
and add a optional request parameter into your controller like below
#RequestMapping(value = "/admin/assign/add", method = RequestMethod.POST)
public String save(#RequestParam("fullname") String fullname,#Valid #ModelAttribute("cafeTable") CafeTable cafeTable) {
//now you can access full name from fullname variable here
....
}
I haven't tested this code.

populating the uploaded file name and size in a html table, appending new values when user choose files at second time

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...

Spring MVC Request Param

I have a login page with form action of j_security_check. As of now this form just have two fields namely username
and password. I want to add a new dropdown to this form and collect the selected value in controller using
#RequestParam. For some reason I am not able to pass this dropdown value from JSP to my controller as its throwing the
exception: MissingServletRequestParameterException (Which occurs anytime a request param is missing).
In the code below I added the Visuals dropdown. Do I need to use Spring:Bind tag here?
Also on successful login, the control is directed to a controller with request mapping /controller1.html and this is where
I am trying to collect the dropdown value.
<form name="appLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table>
<tr>
<td>Username: </td>
<td><input id="userName" name="j_username" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="j_password" type="password" value="" /></td>
</tr>
<tr>
<td>Visual: </td>
<td><Select name="visuals" id="visuals"/>
<option value="S1">S1</option>
<option value="S2">S2</option>
<option value="S3">S3</option>
<option value="S4">S4</option>
</Select>
</td>
</tr>
</table>
<table>
<tr>
<td>
<button type="submit" name="submit" value="Sign In">Sign In</button>
<input type="submit"/>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</form>
Controller Code:
#RequestMapping( value = " /controller1.html", method = RequestMethod.GET )
public String setupForm( #RequestParam(value = "visuals", required=false) String visuals,
ModelMap model )
{
List<String> studentNames = new ArrayList<String>();
List<String> teacherNames = new ArrayList<String>();
model.addAttribute("someData", teacherNames);
model.addAttribute("anotherData", studentNames);
model.addAttribute("visuals", visuals);
log.info("Role from Dropdown: " + visuals);
return "school/classTen";
}
You need to create yyour own Filter by extending AbstractAuthenticationProcessingFilter
I don't have the entire code in front of my eyes, but the following article could help you:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html

Web Flow problems from GET Jsp to a POST JSP (Form) - Spring MVC Annotated

i have a JSP with hyperlink
<table>
<tr>
<td>Product Name : </td>
<td>${product.name}</td>
</tr>
<tr>
<td>Description:</td>
<td>${product.description}</td>
</tr>
<tr>
<td>Price:</td>
<td>${product.price}</td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
Add to shopping basket
</td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
And the controller
#Controller
#SessionAttributes("basket")
public class ShopBasketController {
private BasketManager basketManager;
private CustomerManager customerManager;
private CategoryManager categoryManager;
#Autowired
public ShopBasketController(BasketManager basketManager, CustomerManager customerManager, CategoryManager categoryManager) {
this.basketManager = basketManager;
this.customerManager = customerManager;
this.categoryManager = categoryManager;
}
#RequestMapping(value="/basketItems", method=RequestMethod.POST)
public String removeProduct(#ModelAttribute("basket") Basket basket, BindingResult bindingResult, Model model) {
Basket newBasket = ShoppingBasketUtils.removeFromBasket(basket, basketManager);
basketManager.update(newBasket);
model.addAttribute("basket",newBasket);
model.addAttribute("customer", "Sonx"+" Nkuks");
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(basket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(basket)));
return "basketItems";
}
#RequestMapping("/populateBasket")
public String populateBasket(#RequestParam("code") String productCode, #RequestParam("name") String categoryName, Model model) {
Customer customer = customerManager.getCustomer("Sonx", "Nkuks");
if(customer != null) {
Basket shopBasket = ShoppingBasketUtils.addToBasket(productCode, categoryManager.getCategory(categoryName),
basketManager.getBasket(customer.getReferenceNumber()), basketManager);
basketManager.update(shopBasket);
model.addAttribute("basket",shopBasket);
model.addAttribute("customer", customer.getFirstName()+" "+customer.getLastName());
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(shopBasket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(shopBasket)));
return "basketItems";
}
model.addAttribute("customer", "test".concat(" test"));
return "/error";
}
}
Then the form ...
<form:form commandName="basket">
<table>
<tr>
<td>
<table>
<tr>
<td>Customer Name : </td>
<td>${customer}</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="600" border="1" cellspacing="0" cellpadding="2"
border="0">
<thead>
<tr>
<td>Products:</td>
</tr>
<tr>
<td>Product Name</td>
<td>Product Code</td>
<td>Description</td>
<td>Price</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<c:forEach items="${basket.products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.productCode}</td>
<td>${product.description}</td>
<td>${product.price}</td>
<td><form:checkbox path="removeItemCodes" value="${product.productCode}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>Total Price</td>
<td> </td>
<td>${totalPrice}</td>
</tr>
<tr>
<td>Total Items</td>
<td> </td>
<td>${totalItems}</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td><input type="submit" value="Remove Items" /></td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
</table>
When i press the link from the first JSP "" the controller succesfully execute the method populateBasket and loads the Form. But when i submit the form, i want it to call the POST method (basketItems)... But it doesn't, pressng the submit button always executes the GET method (populateBasket) .. This doesn't happen if i load the form directly from the index page, it loads successfully . Problem is when coming from that JSP ?
If you want the form to submit to a different URL from the one that was used to retrieve the page, you need to explicitly set the action on it. Otherwise Spring is going to just fill it in with the current URL.

Categories