I am using standard spring mvc tags, ala:
<form:input id="startDate" path="startDate" cssClass="datepicker" cssErrorClass="error datepicker" placeholder="Start Date" />
backed by a form object.
My inputs are validated on the serverside, either using annotation based binding on the form object, ala:
#NotNull
getStartDate() {
return this.startDate();
}
or being explicitly rejected, ala:
FieldError fieldErr = new FieldError("theForm", "startDate", "Please check your dates");
BindingResult result.addError(fieldErr);
If an input fails validation, the spring tag correctly adds the cssErrorClass to the input. However, my problem. I'd like the erroneous content to stay populated in the input tag. If 1/1/14 is determined to be invalid, I want the form to be repopulated with 1/1/14 as the value of that input.
So... help? Anyone have a workaround for this? Thanks!
you have 2 options:
1- add the form to model again with same name used in
2- put your form as #SeeeionAttribute, but in this case your form will be stored in session and you will need to clean your session from it after finish of using it.
Related
I have a <form:form> in my jsp page with several <form:input> fields (so, fields are databound). Some of those fields are populated by user, but some, instead of waiting for user to enter some value, need to pre-populated with the value of parameter sent to this page from another jsp page, through the spring controller. How to write that parametar into <form:input> so user doesn't have to?
If I understand your question correctly, you want to prepopulate some fields with values already submitted previously.
All you need to understand is that with the Spring form taglib, Spring expects you to put a command object in the model and will bind the values in that command object to the form fields.
If you don't specify the key for this command object in the model, the taglib will look for it with the key "command". You can specify a different name though with the commandName attribute on the form tag, such as:
<form:form commandName="myModelObject">
Spring would now look for an object in the model named myModelObject to use to bind the form tags.
The other thing you then need to do is in the form tags in your Spring form, reference the fields in your command object. So, for example, let's say your command object has a field firstName, you'd have an input tag like this:
<form:input path="firstName" />
The path attribute tells the attribute what fields in the command object it should bind with.
So then you simply put the command object in your model with the appropriate fields prepopulated and the corresponding form fields will have those values prepopulated. Such as if you put an object in the model with the name myModelObject that has a field firstName, it will be prepopulated with whatever firstName is currently set to in that object.
I am using #Valid for validation during a form submission and encountered error that a property is null. I have a Country class which have properties such as code, name and createdBy all with their predefined values. When user load the page the loaded property on the form are only code and name. After user changes the value and perform submission the value of createdByis null thus validation fails. I am thinking of storing createdBy value in a hidden field on html so the validation should pass. In view of security I think anyone can actually modify the hidden field value. Is there a better approach ? Will OpenSessionInViewFilter helps in any way ?
UPDATED
Sorry that I forgot to mention, the data the browser gets from the server is in form of JSON (List of json object). Before form submission a wrote a JavaScript to populate the form based on the chosen object (with ID) within a html table. So what I send to the server is basically
<input type="hidden" name="id"/>
<html:field name="code" labelCode="label.code" type="text"/>
<html:field name="name" labelCode="label.name" type="text"/>
I am trying to validate 2 model attributes on one action using spring validation framework. The purpose is to validate the lookUpbean (search criterion) on click of Search button and then to validate the resultant bean also i.e memberShipbean once we get it from the services so that we can show warnings to the user if some fields are empty in the resultant bean.
<form:form method="POST" modelAttribute="lookupPageBean" id="lookupForm" name="lookupForm"
action="lookupMembership.htm">
<td class="error">
<form:errors path="membershipNumber" />
<form:input class="medium-textbox" id="membershipNumber" path="membershipNumber" />
<button type="submit" class="Active-button-small">
<fmt:message key="button.go" />
</button>`
#RequestMapping(method = RequestMethod.POST, value = URLMappingConstant.MEMBERSHIP_LOOKUP)
public String viewMembership(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
#ModelAttribute(UIConstant.LOOKUP_PAGE_BEAN) LookupPageBean lookupPageBean, BindingResult result,
#ModelAttribute(UIConstant.MEMBERSHIP_BEAN) MembershipPageBean membershipPageBean, BindingResult error) throws WebMTracksException
{
membershipValidator.validate(lookupPageBean, result);
membershipValidator.validate(membershipPageBean, error);
}
Now what is happening is first validation is working fine however during second validation
the error messages are not shown on the resultant jsp ,
however the errors are reported till this controller layer in the “error” binding results.
Also in the validation layer
ValidationUtils.rejectIfEmpty(errors, UIConstant.BUSINESSNAME,ValidationMSGConstants.BUSINESS_NAME)
This method always returns validation errors even if the field is not empty.
First question is can we have multiple model attributes in one action. I read it somewhere on internet but could not find any implementation of the same. Please help me to resolve this issue. Also let me know if you can think of any other working solution for this problem but I would like to use only the spring framework for the both the validations as that helps to maintain the existing design of the application.
I do not think you have bind multiple Model Attributes to the same form, which I believe is what you are asking. I am not even sure what that request would look like, from an HTTP stand point, as I don't believe Spring would have a way to detangle all the bean's properties, especially if the names overlap. What you may want to consider doing is wrapping your LookupPageBean and MembershipPageBean into one "form bean".
As for the error messages, you may want to take a look at the spring:bind tag. It may do what you are needed to get the binding errors from the second Model Attribute.
I'm looking for a very simple form processing API for Java. Assuming the form input fields correspond to bean properties, and all beans have javax.Validation annotations, ideally the API would:
Display a bean as an html form
Populate the bean, including nested objects where applicable, using the request parameters
Validate the input using Validation annotation
If there is an error, display errors at top of form, and highlight error fields.
Additionally:
It would be nice if i didn't have to buy into a whole application framework, since I am working with a legacy app.
Allow configuration for more complicated use cases, but by default just use convention.
Bonus:
generates javascript client side validation too.
Note: If this requires several different libraries, that is fine too.
Update:
Since I never found what I was looking for, and migrating to Spring was not an option, I went ahead and rolled my own solution. It is, affectionately, called java in jails (loosely modeled on rails form processing). It gives you dead simple (and pretty) form creation, client and server side validation, and request parameter to object mapping. No configuration required.
Example Bean:
public class AccountForm {
#NotBlank(groups = RequiredChecks.class)
#Size(min = 2, max = 25)
private String name;
//...
}
Example Form:
<%# taglib uri="http://org.jails.org/form/taglib" prefix="s" %>
<s:form name="accountForm" action="/jails-demo/jails" label="Your Account Details" style="side">
<s:text name="name" label="Name" size="25" />
<s:text name="accountName" label="Account Name" size="15" />
...
</s:form>
Example Validation and Mapping:
SimpleValidator validator = new SimpleValidator();
if ("submit".equals(request.getParameter("submit"))) {
Map<String, List<String>> errors = validator.validate(AccountForm.class, request.getParameterMap());
if (errors != null) {
AccountForm account = validator.getMapper().toObject(AccountForm.class, request.getParameterMap());
//do something with valid account
} else {
SimpleForm.validateAs(AccountForm.class).inRequest(request).setErrors(errors);
//handle error
}
} else {
SimpleForm.validateAs(AccountForm.class).inRequest(request);
//forward to formPage
}
This is what the form looks like, with client side validation using jQuery (provided by Position Absolute):
I don't think you will find something that has most of this functionality and is not a framework.
I can recommend Spring MVC - you can plug it in easily in the legacy app. It supports all of the above.
Doing-it-yourself won't be that hard either:
use BeanUtils.populate(bean, request.getParameterMap()) to fill your object with the request parameters
use javax.validation.* manually - here is how. For each error add request attributes which you can later display as errors.
Note that either way you will have to write the html code manually.
Hi i am building a webapp with struts 1.2
I am building an "edit" form, so i have my input tags being pre populated from a bean:
form.jsp
<html:text property="population"
value="${city.population}"/>
Later on, i use struts validation
The problem is, i have 10 form elements, if one of them fails by the validation rules, the action gets back to the form and populates de elements with the bean data and not with the resently changed data of the user.
I wan
The problem is due to the value attribute you have there. The property attribute should be enough to show the correct value in the input. Having value there will always cause the value of ${city.population} to be displayed.