Spring Framework 3.0.5 - spring form data binding - comma delimiter - spring

I have a group editation form:
<form:form method="POST" action="" commandName="group">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" disabled="disabled" /></td>
<td><form:errors path="name" class="error" /></td>
</tr>
<tr>
<td><form:label path="description">Description</form:label></td>
<td><form:input path="description" /></td>
<td><form:errors path="description" class="error" /></td>
</tr>
<tr>
<td><form:label path="gidNumber">GID</form:label></td>
<td><form:input path="gidNumber" /></td>
<td><form:errors path="gidNumber" class="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
<form:hidden path="members" />
</form:form>
This form is binding object of class Group. Problem is with binding the member attribute to the hidden field. The deffinition of the memeber attribute in Group class is below. The group class is also being used by Spring LDAP ODM manager, (thus the annotations there).
#Attribute(name="member", syntax="1.3.6.1.4.1.1466.115.121.1.12")
private List<String> members = new ArrayList<String>();
The content of this array list is usually something like:
1: uid=user1,ou=users,dc=example,dc=com
2: uid=lilcuttie2,ou=users,dc=example,dc=com
3: uid=naprostejmagor,ou=users,dc=example,dc=com
4: uid=crazyuser,ou=users,dc=brazzers,dc=com
...
When the content is binded to hidden field it is concatenated to the comma delimited and then when it is beeing splited again to the arraylist entries, of course each entry is broken to four separate entries.
I've tried to use custom converter for ArrayList, but it messed up some otheer stuf like loading resource messages for locales..
Do you have any suggestions how to deal with it in any non-ugly way - so that I dont have to wrap my DAO classes nor modify them.
Thanks,
/Jakub

Have a small wrapper type over your members element, say:
public class MembersWrapper{
private List<String> members;
.....
}
Now, you can provide a custom converter to convert this MembersWrapper instance to a String and back - the conversion can be to say colon delimited across each element of the list, something that you can parse back later:
public class MemberWrapperToStringConverter implements Converter<MemberWrapper, String>{
...
}
public class StringToMemberWrapperConverter implements Converter<String, MemberWrapper>{
....
}
and register these converters with Spring MVC:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="..MemberWrapperToStringConverter "/>
<bean class="..StringToMemberWrapperConverter "/>
</set>
</property>
</bean>
An alternative will be providing a custom property editor through #InitBinder annotation:
#InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Wrapper.class, new PropertyEditorSupport(){
#Override public String getAsText() {
//....
}
#Override public void setAsText(String text) throws IllegalArgumentException {
//....
}
});
}
The logic in these converters should be straightforward, convert the list to some string form, that you can parse back to list easily, say between list elements just add a colon or a semi-colon.

As I am not clear about your problem I have made some assumptions and providing this answer on basis of that.
Well you can use to loop your entries in the members list and for each entry in the list you can create a separate hidden field for that.
Hope this helps you.
Cheers.

You don't need to put the formtag for hidden field now when you are using just use the simple input tag for hidden fields but in the name property you need to specify as following.
<input type="hidden" name="members${status.index}"/>
in this way it will bind the same value back to the controller.
I think this should help you.
Cheers.

Related

Extra character(,) is added while using Textbox in spring

I am new to JSP and Spring. I want to insert a userID(U0005) using textbox in spring form but it is storing(,U0005). From where the "," is inserted?
The code I have written is:
/* In Register.jsp: */
<c:url var="addAction" value="/libUsr/add"></c:url>
<form:form action="${addAction}" commandName="libUsr">
<table>
<tr>
<td>
<form:label path="id">
<spring:message text="ID" />
</form:label>
</td>
<td><form:input path="id" required="true" /></td>
</tr>
</table>
</form:form>
/*
In UserController.java:
*/
#RequestMapping(value= "/libUsr/add", method = RequestMethod.POST)
public String addLibUsr(#ModelAttribute("libUsr") LibUsr libUsr){
libUsrDAO.saveOrUpdate(libUsr);
return "redirect:/register";
}
/*
In DAOImpl:
Saving the data through DAOs
*/
#Transactional
public void saveOrUpdate(LibUsr libusr) {
sessionFactory.getCurrentSession().saveOrUpdate(libusr);
}
Your problem is with this tag:
<form:label path="id">
As you are adding the attribute path to one label, which wont store any value, spring try to get the value and returns empty,yourID.
Change the path attribute of your label to:
<form:label for="id">
<spring:message text="ID" />
</form:label>
If you want to show the value of the id into that label use:
<label>${yourObject.id}</label>
or
<label th:value="${yourObject.id}"></label>
Path attribute is just for input, select, checkbox...not static values as label, span...

How to get data from two classes that are many-to-many, in the same edit form?

I am working with two classes that have a relationship many-to-many. I insert data in both tables, the relationship is usually registered in JoinTable. My question is, how to display the data from both tables in the same form?
Here is my controller:
#Controller
public class RecipeController {
#Autowired
private ReceitaService receitaService;
#RequestMapping(value = "/novaReceita.do", method = RequestMethod.POST)
public String createRecipes(#ModelAttribute("Receita") Receita receita, BindingResult resultReceita,
#ModelAttribute("Tag") Tag tag, BindingResult resultTag, #RequestParam String action, Map<String, Object> map) {
receita.getTag().add(tag);
receitaService.addReceita(receita);
map.put("receita", receita);
map.put("receitaList", receitaService.getAllReceita());
return "listRecipes";
}
Here is where I am having problems because I can only show data for a single table.
public String editForm(#PathVariable("id") int id, ModelMap map) {
map.addAttribute("receita", receitaService.getReceita(id));
return "updateRecipes";
}
Finally, the JSP page to display the data entered:
<c:url var="url" value="/receita/${receita.id}"/>
<form:form action="${url}" method="GET" commandName="receita">
<table width=80% >
<tr>
<td><strong>ID </strong></td>
<td><form:input path="id" disabled="true" class="input-small"/></td>
</tr>
<tr>
<td><strong>Title </strong></td>
<td><form:input path="titulo" class="input-xlarge"/></td>
</tr>
<tr>
<td valign=top><strong>Desc probl</strong></td>
<td><form:textarea path="desc_prob" class="input-xlarge" rows="3" /></td>
</tr>
<tr>
<td valign=top><strong>Desc soluc</strong></td>
<td><form:textarea path="desc_soluc" class="input-xlarge" rows="6" /></td>
</tr>
<tr>
<td><strong>Tag</strong></td>
<td> <form:input path="tag" disabled="true" class="input-small"/></td>
</tr>
</table>
</form:form>
What is missing to be able to show the data from both tables?
Thank's.
For single column/property you can use <form:input/>For Many to One you can use <form:select/>For One to Many you can use <form:select multiple='true'>In your case, you have to select a single ID first for the one side of the relationship which is receita and then display all the tags in that receita, so i think it counts as One to Many at that point. So in your case, try to use this tag:<form:select path="tag" multiple="true"/>

Spring MVC: list of checkboxes not returned to controller on POST

Why doesn't the server see my list of filled checkboxes?
This question seems to be here asked many times, but the details are so different for each requester that it seems a different answer is needed each time. Here is my story.
These are my data-bearing classes. The Offer contains a list of Filter objects in the filter attribute:.
public class Offer implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id = null;
#Column(name="title")
private String title = null;
[snip]
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name = "offer_filter",
joinColumns = { #JoinColumn(name = "offer_id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "filter_id", nullable = false, updatable = false) })
private List<Filter> filters;
[snip]
}
public class Filter implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id;
#NotBlank
#Length(max=100)
#Column(name="text")
private String text;
[snip]
#Transient
private boolean owned = false;
[snip]
}
The simple controller sends the offerEdit.jsp page, with a fully-populated Offer object. The object contains a list of Filters. Because of the owned attribute, only one of the three Filters is pre-checked. This simulates my eventual plan, where the list of Filters is the whole universe and what the Offer owns is a subset.
Note the annotations, that the Offer has the filter list going to the web page but doesn't see it coming back.
public class OfferController {
[snip]
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("id") Long id, Model model, HttpSession session) {
Offer offerAttribute = offerService.get(id);
// At this point, offerAttribute.filters has three elements.
// Mockup -- tells web page that only the middle one of the three Filters should be checked.
List<Filter> filters = offer.getFilters();
Filter filter = filters.get(1);
filter.setOwned(true);
model.addAttribute("offerAttribute", offerAttribute);
return "offer/offerEdit";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("id") Long id, #Valid #ModelAttribute("offerAttribute") Offer offerAttribute, BindingResult result, HttpSession session, Model model) {
// At this point, offerAttribute.filters is null.
if(result.hasErrors()) {
result.reject("offer.invalidFields");
return "offer/offerEdit";
}
offerAttribute.setId(id);
offerService.edit(offerAttribute);
return "redirect:/offer/list";
}
[snip]
}
The web page has this for its checkbox section. I use form:checkbox over form:checkboxes because I want to use a table,
[snip]
<form:form modelAttribute="offerAttribute" method="POST" action="${saveUrl}">
<table>
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td><form:label path="title">Title:</form:label></td>
<td><form:input path="title" size="80" /></td>
<td><form:errors path="title" cssClass="error" /></td>
</tr>
[snip]
</table>
<table>
</table>
<table>
<c:forEach items="${offerAttribute.filters}" var="filter">
<tr>
<td><form:checkbox
path="filters"
label="${filter.text}"
value="${filter.id}"
checked="${filter.owned ? 'true' : ''}" />
</td>
</tr>
</c:forEach>
</table>
[snip]
The displayed web page has three filter checkboxes displayed, with just the middle checkbox filled in.
For the returned list, I expect the server to get only the middle checkbox, which is just what I want.
Here is what the generated checkboxes look like as source:
<table style="border: 1px solid; width: 100%; text-align:left;">
<tr>
<td>
<input id="filters1" name="filters" type="checkbox" value="1"/>
<label for="filters1">Adults (18+) desired, please</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
<tr>
<td>
<input id="filters2" name="filters" checked="true" type="checkbox" value="2"/>
<label for="filters2">Quiet audiences, please</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
<tr>
<td>
<input id="filters3" name="filters" type="checkbox" value="4"/>
<label for="filters3">Filter Text First</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
</table>
My checkbox is set, and in the HTML. To restate my question,
Why doesn't the checkbox value get seen in the controller's POST handler?
Thanks for any answers,
Jerome.
The values of checkboxes could not be directly bind to List.
To get this working you need to create a simple pojo databean that will hold the values of your form fields in jsp. And in that databean to bind the values you need to declare int[] filterId and the values of your checkboxes will bind in that array.
Hope this helps you.
After a lot of web research and different debugging sessions, I came up with a configuration I can live with.
In my controller I provide a model attribute of "filterList", containing List. The "offerAttribute" is an Offer object, containing List filters.
The view has this sequence:
<table>
<c:forEach items="${filterList}" var="filter" varStatus="status">
<tr>
<td><input type="checkbox" name="filters[${status.index}].id"
value="${filter.id}"
${filter.owned ? 'checked' : ''} /> ${filter.text}
</td>
</tr>
</c:forEach>
</table>
When the POST is done the ownerAttribute.filters list is just as long as the original filterList object that created the checkboxes. The checked ones contains a Filter.id value. The unchecked ones contain a null. (That is, the returned filters list is "sparse".) If the user clicks on just a few checkboxes then I must parse the returned list to find those that were chosen.
Once I know the ID values of the checked-on filters, I fetch each of them through Hibernate, put them into my reconstructed Offer object and then persist them to the database.
I realize that I'm not (currently) using the form:checkbox. But it works, and I'm pressed for time here. I'll come back later, perhaps, and see what form:checkbox can do for me.

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.

Why do I get IllegalArgumentException Cannot convert value of type String to required type Product, in Spring?

I receive the exception
Failed to convert property value of
type [java.lang.String] to required
type [beans.Product] for property
product; nested exception is
java.lang.IllegalArgumentException:
Cannot convert value of type
[java.lang.String] to required type
[beans.Product] for property product:
no matching editors or conversion
strategy found
in the Errors errors object even before my DetailProductValidator starts validating through the validate method.
I don't understand why Spring does that. I don't have any input field that is mapped directly to the product property/object. I just use the product object's properties in the jsp. For example, I use:
<form:options items="${dpBackObj.product.colorMap}"/>
<!-- or -->
${dpBackObj.product.priceInDollars}
but I never use:
<form:input path="product"/>
Can anyone please explain why this happens? And maybe inform me of a simple solution?
The bean configuration for the controller is:
<!-- DETAIL PRODUCT FORM CONTROLLER -->
<bean id="productDetailFormController" name="/detail.htm /addToCart.htm"
class="detailProduct.DetailProductFormController">
<property name="sessionForm" value="true" />
<property name="commandName" value="dpBackObj" />
<property name="commandClass" value="detailProduct.DetailProductBackingObject" />
<property name="validator">
<bean class="detailProduct.DetailProductValidator" />
</property>
<property name="formView" value="detail" />
<property name="successView" value="redirect:/viewCart.htm" />
<property name="cartService" ref="cartServiceImpl"/>
</bean>
The backing object for the DetailProductFormController is:
public class DetailProductBackingObject {
private String quantityOverflowError;
private Product product;
private int quantity;
private ShoppingCart shoppingCart;
private long sizeId;
private long colorId;
public DetailProductBackingObject() {
this.product = new Product();
this.sizeId = -1;
this.colorId = -1;
}
//getters and setters
}
If you need some other info, I will provide. I am using Spring 2.5.5.
Kind Regards,
Despot
EDIT1 (due to request from axtavt):
<form:form method="post" commandName="dpBackObj">
<table width="730" border="0" cellspacing="0" cellpadding="0">
<c:if test="${!empty dpBackObj.quantityOverflowError}">
<tr>
<td>
<c:out value="${dpBackObj.quantityOverflowError}"/>
</td>
</tr>
</c:if>
<spring:bind path="dpBackObj.*">
<c:if test="${not empty status.errorMessages}">
<div class="val-summary text-error" id="errorDivId">
<div style="" class="val-summary text-error" id="errorDivId">
<fmt:message key="detail.error.header"/>
<ul>
<c:forEach items="${status.errorMessages}" var="error">
<li><c:out value="${error}"/></li>
</c:forEach>
</ul>
</div>
</div>
</c:if>
</spring:bind>
<tr>
<td width="310" align="left" valign="top">
<img src="${imagesPath}/${dpBackObj.product.largeImageUrl}" alt="${dpBackObj.product.description}" />
</td>
<td width="420" align="left" valign="top">
<div id="tls_detPName">
<c:out value="${dpBackObj.product.name}"></c:out>
</div>
<div >
<strong class="numeric">${dpBackObj.product.priceInDollars}</strong>
</div>
<div id="tls_detPDescLong">
${dpBackObj.product.largeDescription}
<br />
</div>
<div >
<table cellpadding="2" border="0">
<tr>
<td align="right">
<label for="p_sizes" class="label"><fmt:message key="viewCart.Size"/></label>
</td>
<td>
<form:select path="sizeId" >
<form:option value="-1" label="x"/>
<form:options items="${dpBackObj.product.sizeMap}"/>
</form:select>
</td>
</tr>
<tr>
<td align="right">
<label for="p_colors" class="label"><fmt:message key="viewCart.Color"/></label>
</td>
<td>
<form:select path="colorId" >
<form:option value="-1" label="y"/>
<form:options items="${dpBackObj.product.colorMap}"/>
</form:select>
</td>
</tr>
</table>
</div>
<div id="tls_addToCart">
<div >
<label for="quantityId" class="label"><fmt:message key="viewCart.Quantity"/>:</label>
<form:input path="quantity" onkeypress="return checkForNumber(this, event)" maxlength="10" size="3" id="quantityId" cssClass="textbox-center"/>
<input type="image" name="addToCartButtonName" src="${imagesPath}/addToCartBtn.jpg" />
</div>
</div>
</td>
</tr>
</table>
</form:form>
EDIT2 (due to JacobM's request):
This is my Validator:
public class DetailProductValidator implements Validator {
public boolean supports(Class clazz) {
return DetailProductBackingObject.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
DetailProductBackingObject detailProductBackingObject = (DetailProductBackingObject) obj;
if (detailProductBackingObject.getSizeId() == -1) {
errors.rejectValue("sizeId", "error.detail.jsp.choose.size", null, "Input size.");
}
}
}
When I reach the line DetailProductBackingObject detailProductBackingObject = I already have the error.
The converting of the request parameters to the backing object properties happens in http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/mvc/BaseCommandController.html . This is what Spring says about the conversion:
Populating using request parameters
and PropertyEditors: Upon receiving a
request, any BaseCommandController
will attempt to fill the command
object using the request parameters.
This is done using the typical and
well-known JavaBeans property
notation. When a request parameter
named 'firstName' exists, the
framework will attempt to call
setFirstName([value]) passing the
value of the parameter. Nested
properties are of course supported.
For instance a parameter named
'address.city' will result in a
getAddress().setCity([value]) call on
the command class.
It's important to realise that you are
not limited to String arguments in
your JavaBeans. Using the
PropertyEditor-notion as supplied by
the java.beans package, you will be
able to transform Strings to Objects
and the other way around. For instance
setLocale(Locale loc) is perfectly
possible for a request parameter named
locale having a value of en, as long
as you register the appropriate
PropertyEditor in the Controller (see
initBinder() for more information on
that matter.
Validators: After the controller has
successfully populated the command
object with parameters from the
request, it will use any configured
validators to validate the object.
Validation results will be put in a
Errors object which can be used in a
View to render any input problems.
Since I can't see anything wrong with the form, the only possible reason I can imagine is that you have a parameter named product in the URL of your form page.
If so, you can change your URLs or use DataBinder.setDisallowedFields() to disable the attempt to bind that parameter.

Resources