ModelAttribute returns null values in controller in Spring MVC - spring

Ok, its time to seek help; I am sending a (shopping) Cart ModelAttribute to my jsp, allowing the user to edit the quantity, when the Model is POST to the controller the fields are null except the editable (quantity) field. I have researched for days on similar issues but nothing is matching. I am using spring 3.1.
Here is my controller on the GET and POST:
#Controller
public class CartController {
#Autowired
private Cart cart;
#RequestMapping(value = "/cart", method = RequestMethod.GET)
public String showCart(Model model) {
logger.debug("CartController.showCart() Cart: {}", this.cart);
model.addAttribute(cart);
return "cart/cart";
}
and POST
#RequestMapping(value = "/cart", method = RequestMethod.POST, params = "update")
public String update(#ModelAttribute("cart") Cart cart, BindingResult result, Model model) {
logger.debug("CartController.update() Cart: {}", cart);
return "cart/cart";
}
my jsp:
<div class="container MainContent">
<form:form method="POST" modelAttribute="cart">
<fieldset>
<legend>Cart</legend>
<table class="table">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<c:forEach items="${cart.cartDetails}" var="cartDetail" varStatus="status">
<tr>
<td>${cartDetail.product.name}</td>
<td><form:input path="cartDetails[${status.index}].quantity" size="1" /></td>
<td>${cartDetail.price}</td>
</c:forEach>
<tr>
<b><td colspan="2" align="right"><spring:message code="order.total" /></b>
</td>
<td>${cart.totalCartPrice}</td>
</tr>
</tbody>
</table>
</fieldset>
<div></div>
<button id="order" name="order">
<spring:message code="button.order" />
</button>
<button id="update" name="update">
<spring:message code="button.update" />
</button>
</form:form>
</div>
and the log results for cart before on GET:
CartController.showCart() Cart: Cart [cartDetails=[CartDetail
product=com.Product#c26440[name=My Name],
quantity=1]], totalCartPrice=10.00]
and after updating the quantity from 1 to 3 in the jsp and then POST to the controller:
CartController.update() Cart: Cart [cartDetails=[CartDetail
[product=null, quantity=3]], totalCartPrice=null]
I've read several similar post here and on the Spring forum and tried different suggested solutions with no luck. It seems like my edited quantity results are getting bound to the Object correctly but why aren’t the others?

Assuming you have all the necessary fields in your Form object;
You have to specify the form fields and fill the value with your data.
<td>${cartDetail.product.name}</td>
will only print the result to the screen. If you want to bind it to your form you have to put it in a spring form input such as:
<form:input path="productName" value="${cartDetail.product.name}"/>
If you don't want it to be editable then you can put it into a hidden field but in the end you'll have to put it in a form element in the jsp and have a corresponding field in your form POJO

Seems other fields aren't bound, try to bind for example product name
<td>${cartDetail.product.name}
<form:hidden path="cartDetails[${status.index}].product.name" value="${cartDetail.product.name}"/></td>

I once spent a lot of time investigating a similar issue. Finally I found the culprit inside a Binder's initialization method:
#InitBinder
void initBinder(final WebDataBinder binder) {
binder.setAllowedFields("name", ...);
}
This method sets a restriction on fields that are allowed for binding. And all the other fields are unbound, naturally resulting in null values.
The other possible reason: incorrect setters in a Bean annotated with #ModelAttribute. For example, Object setName(String name) instead of void setName(String).

Related

Redirect on controller advice expectionhandler with model attribute spring MVC

So i try to redirect from ExceptionHandler wit model attribute to the site where it was caused.
For example i have a controller method witch list the current items:
#AvailableInMenu
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("Companys", iCompanyService.findAll().getData());
return "masters/crud/company/list";
}
An this is the template witch the method call:
<div th:if="${exception != null}" class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong><div th:text="${exception}" th:remove="tag" ></div>
</div>
<div class="ibox float-e-margins">
<div class="ibox-content">
<table id="table" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th th:text="#{app.maintanance.installversion}"></th>
</tr>
</thead>
<tbody>
<tr th:each="company : ${Companys}">
<td th:text="${company.installversion}"></td>
<td>
<a class="delete-button" th:attr="data-redir=#{/company/delete/{id}(id = ${company.id})}">
<i class="fa fa-pencil"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
This thymeleaf code generate a table with data and a delete link. Th entity wotch the user use has foreign key, and if the user want to delete it jpa thows a foreign key constraint witch i wrap into an error wrapper.
This is the controller method for the delete link:
#RequestMapping(value = {"/delete/{id}"}, method = RequestMethod.GET)
public String deleteCompany(Model model, #PathVariable("id") Long id) {
ErrorWrapper<Boolean> result = iCompanyService.deleteCompany(id);
if(result.hasError()){
if(result.getConstraint()){
throw new GlobalModelException(601L, "redirect:/company");
}
}
return "redirect:/company";
}
AS you can see if there was an error i throw general exception that i create, and a ControllerAdvice with ExpectonHandler where is catch my expection class. I want to add the exception to model and redirect back to the listing site, and show the bootstrap alert to the on the site.
This is the exceptionHandler from the ControllerAdvice
#ExceptionHandler(GlobalModelException.class)
public ModelAndView handlingException(GlobalModelException exception) {
ModelAndView model = new ModelAndView();
model.setViewName(exception.getUrl());
model.addObject("exception", exception);
return model;
}
The ModelAndView redirect me the correct place as it should be, but the exception is null after redirect. How can i call my listing site with the exception in the model with ControllerADvice. I have many other exceptions that i want to handle and a a lot of other controller where i need this.
Is there any way to do this?
You mush use RedirectAttributes/FlashAttribute.
http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/
http://www.baeldung.com/spring-redirect-and-forward

How to modify a record displaying a form in a view

I am trying to accomplish the following:
I have a list of fruits, that are stored in a table with two columns "id", "name" and "color".
Next to each fruit, I got a "modify" button. What I want to do here is being able to display the fruit in a form and being able to modify the "name" and "color" attributes.
I don't understand why, but when I click the "modify" button, the form is being displayed but the properties of the fruits that I clicked are not.
Here is the code:
Controller:
#RequestMapping(value = "/fruit/modify", method = RequestMethod.POST)
public String modifyFruit( #RequestParam("id") int id, ModelMap model) {
Fruit fruit = fruitManager.getFruitById(id);
model.addAttribute("fruit", fruit);
return "redirect:/modifyfruit";
}
#RequestMapping(value = "/modifyfruit", method = RequestMethod.GET)
public String showAddForm(#ModelAttribute("fruit") Fruit fruit, ModelMap model) {
model.addAttribute("fruit", fruit);
return "/secure/modifyfruit";
}
Here is the modify button that I am displaying next to each fruit in my list:
<td>
<c:url var="modifyUrl" value="/fruit/modify.html"/>
<form id="${fruitForm}" action="${modifyUrl}" method="POST">
<input id="id" name="id" type="hidden" value="${fruit.id}"/>
<input type="submit" value="modify"/>
</form>
</td>
Here is the modifyfruit.jsp that I am using to display the form that I want to populate:
<body>
<form:form method="post" commandName="fruit">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0"
cellpadding="5">
<tr>
<td align="right">Name:</td>
<td><form:input path="title" value="${fruit.name}"/></td>
</tr>
<tr>
<td align="right">Color:</td>
<td><form:input path="color" value="${fruit.color}"/></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Post Ad">
</form:form>
</body>
Your redirect is simply going to that new URL without any request params being added. Therefore your fruit ID is being discarded, which is why nothing gets displayed.
The redirect seems pointless - why not return the same view name string as the GET version instead?
To redirect with the params, try:
return "redirect:/modifyfruit?id=" + id;
EDIT: just noticed you have added the Fruit to the model - this does not get transferred in a redirect and wouldn't work anyway.

How to parse spring post data in rest?

I am developing an application in which i am using spring framework 3.1.1 and rest api. In it i have developed one rest controller which will on receiving "GET" request of url "/rest/host/{id}" will redirect the control to my view(form). Now after user fills up the form the posted data is also handled using rest. But in the method which i have written to handle post request all the parameters i am getting in one string which i want to parse and insert into the database. Can anybody tell which is the proper way to parse this spring data ? I can do it using String.split("&") but i don't think it is correct way to do that. Here is my code.
<form:form method="POST" action="/nagios-sms-1.0/rest/snooze/host/" commandName="snoozeBean">
<table width="100%" border="5" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="50%" border="5">
<tr>
<td colspan="3"></td>
</tr>
<tr>
<td width="30%"><form:label path="contactNumber">Enter host address</form:label></td>
<td width="30%"><form:input path="contactNumber" /></td>
<td />
</tr>
<tr>
<td width="30%"><form:label path="snoozeTimeoutValue">Enter Snooze time</form:label></td>
<td width="30%"><form:input path="snoozeTimeoutValue" /></td>
<td />
</tr>
<tr>
<td colspan="3">
<div id="buttons"
style="margin-left: 20Px; margin-right: 100px;">
<input type="submit" value="ok" /> <input type="reset" />
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
REST code..
1) GET handler method
#RequestMapping(value = "/host/{hostId}", method = RequestMethod.GET)
public String snoozeHost(#PathVariable int hostId, ModelMap map) {
Snooze snooze = new Snooze();
snooze.setHost_id(hostId);
map.put("snoozeBean", snooze);
return "host";
}
2) POST handler method
#RequestMapping(value = "/host", method = RequestMethod.POST)
#ResponseBody
public String snoozeHostOK(#RequestBody String payload) {
// i want to parse this payload data which contains my form fields.
System.out.println("data : " + payload);
return payload;
}
Any kind of help will be appreciated. Thanks in advance.
Instead of request body you can use #ModelAttribute and get all the form data bind in one pojo(snooze) filled by Spring Framework on post of the form.
You need to declare snooze in your get and post request mapped method as #ModelAttribute. That will let you get all your values from the form.
UPDATE
See your modified code here.
GET handler method
#RequestMapping(value = "/host/{hostId}", method = RequestMethod.GET)
public String snoozeHost(#PathVariable int hostId, #ModelAttribute Snooze snooze, ModelMap map) {
snooze.setHost_id(hostId);
return "host";
}
POST handler method
#RequestMapping(value = "/host", method = RequestMethod.POST)
#ResponseBody
public String snoozeHostOK(#ModelAttribute Snooze snooze) {
// you can use the setter methods of snooze object to retrieve the field values.
return payload;
}
Hope this helps you. Cheers.

Spring MVC 3 Validation will not work when attributes added to model

I'm trying to get Spring annotation based validation working in a simple webapp. I'm using Spring 3.0.5, Tiles 2.2.2. In one specific case I can get the validation error to appear next to the field, however as soon as I add any objects to the model it stops working. Ideally, after the POST, I want to redirect to a GET of the form with the validation errors included. This is the setup:
I have a simple domain object.
public class DomainObject {
#NotEmpty
private String name;
private Date created;
private Date lastModified;
...
}
I have a controller with a GET method which adds all existing DomainObjects to the model and returns a view that displays them, and contains a very simple form for creating them. It also has a POST method for creating a new DomainObject.
#Controller
#RequestMapping("/")
public class DomainObjectController {
#Autowired
private DomainObjectService domainObjectService;
#RequestMapping("form.htm")
public String home(Model model) {
model.addAttribute("objects", domainObjectService.getAll());
model.addAttribute(new DomainObject());
return "form";
}
#RequestMapping(value="new_object.do", method=RequestMethod.POST)
public String newObject(#Valid DomainObject domainObject, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
//model.addAttribute("objects", domainObjectService.getAll());
//model.addAttribute(new DomainObject());
return "form";
}
domainObjectService.saveNew(domainObject);
model.addAttribute("objects", domainObjectService.getAll());
model.addAttribute(new DomainObject());
return "form";
}
}
Here's the view:
<form:form commandName="domainObject" action="new_object.do" method="post>
<spring:message code="name" />: <form:input path="name" />
<input type="submit" value="<spring:message code="create.object"/>" /><form:errors path="name" cssClass="error"/></form:form>
</div>
<table class="centered">
<col width=50 />
<col width=225 />
<col width=200 />
<col width=200 />
<thead>
<tr>
<td id="id" class="sortable"><spring:message code="id" /></td>
<td id="name" class="sortable"><spring:message code="name" /></td>
<td id="created" class="sortable"><spring:message code="created" /></td>
</tr>
</thead>
<tbody>
<c:forEach var="obj" items="${objects}">
<tr>
<td class="id">${obj.id}</td>
<td>${obj.name}</td>
<td>${obj.created}</td>
</tr>
</c:forEach>
</tbody>
</table>
With this setup, if I leave the name field empty, the validation error is picked up and correctly displayed to the right of the field. However, the table is always empty, as no objects are added to the model. If I add objects to the model, by uncommenting the lines
//model.addAttribute("objects", domainObjectService.getAll());
//model.addAttribute(new DomainObject());
the table is populated but the validation error no longer appears. I can't work this one out.
As another unwanted side effect, any relative links I have in the view now no longer work (for example, a link which changes the locale href="?lang=de").
So, what could be causing the validation message to disappear when I add data to the model? And is it possible for me to redirect to the original form while keeping hold of the validation messages?
Thanks,
Russell
The validation error is attached to the object that is invalid. If you replace the object that is invalide by an new one:
model.addAttribute(newDomainObject());
then the error messages is not attached to this object.

requesting parameters from jsp

I have some problems with taking a parameters from jsp page, when method POST occurs.
My JSP page looks like this:
....
<table border="1">
<tr>
<th>name</th>
<th>check</th>
</tr>
<c:forEach items="${things}" var="pair">
<tr>
<td>${things.name}</td>
<td><INPUT TYPE="CHECKBOX" NAME=items VALUE=${things.id} ></td>
</tr>
</c:forEach>
</table>
<form method="post">
<input type="submit" value="Check all" />
</form>
So, I want to take all checked "things" in table. In controller class I something like this (written in Spring):
....
#RequestMapping(method = RequestMethod.POST)
public String sumbitForm(#RequestParam("items") String[] items){
if(items!= null){
for(String item: items){
....
}
}
return "redirect:myPage";
}
But my app don't want to work with such RequesParam. It doesn't put the values of items parameter to it. (this method I took here http://www.go4expert.com/forums/showthread.php?t=4542)
Also I tried using #ModelAttribute instead of #RequesParam. When I'm using it, my app don't give a errors, but it also couldn't correctly put the "items" to this parameter.
Any ideas?
P.S. May be you know more better method of taking list of parameters from JSP page for using their values (like taking checked items)?
Your table is outside of the <form></form> so when submitting, it doesnt send anything.

Resources