Wrapping PropertyEdtior exceptions during Spring validation - spring

When I submit a Spring form and a PropertyEditor fails to convert a value, an exception is thrown and a message like this ends up in my validator errors object:
Failed to convert property value of type java.lang.String to required type
org.joda.time.DateMidnight for property startDate; nested exception is
java.lang.IllegalArgumentException: Invalid format: "2010-111" is malformed at "1"
Can I wrap this somehow, providing a friendlier message to display on screen?
I'm using #Valid in my controller, with the following in my form:
#NotNull
protected DateMidnight startDate;
Thanks

This error message has message codes such as typeMismatch.objectName.startDate (see DefaultMessageCodesResolver). To display a user-friendly message, you need to declare a MessageSource with the corresponding messages.

Related

Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for prope

I am building a web application using Thymeleaf and SpringBoot, I am new to both the technologies.
In my html file, there is a Date field as follows:
<input type="date" th:field="*{issueDate}" />
My model class has a field corresponding to issueDate as follows:
#NotNull(message = "Cannot be empty")
private Date issueDate;
When I input a date from the UI, I see the following exception in the browser:
Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property issueDate;
From my experience, I understand that the UI reads the property as a String, but the model expects a type Date due to which the error occurs. So I need to convert the String to a Date. However where should this be done? Since the error occurs even before the setter method in the model is invoked.
Any help would be much appreciated! Thanks in advance!
In your controller:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}
WHERE "MM/dd/yyyy" is the date format you're using.

Optional form fields in spring-mvc liferay portlet application

I have a big form with a lot of date fields and int fields
my action phase methos is like this:
public void createCamapign(WebRequest request,ActionResponse response ,
Model model, #ModelAttribute("searchForm") CreateCampaignForm form) throws Exception{
where the form is my wrapper bean
anyway if i dont fill all the fields in the rendered form my application crashed with this error
[org.springframework.web.portlet.DispatcherPortlet] - Handler execution resulted in exception - forwarding to resolved error view
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'searchForm' on field 'activationDate': rejected value []; codes [typeMismatch.searchForm.activationDate,typeMismatch.activationDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [searchForm.activationDate,activationDate]; arguments []; default message [activationDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'activationDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'activationDate': no matching editors or conversion strategy found]
how or where do i specify that these fields are optional
by the way in the case of int fields i kinda resolved it by using Integer class, but i dont want to do the same with Date type attributes
I am not sure if I understood your problem correctly. I am not an expert in Spring.
Just a suggestion, like can you make use of dependency check and #Required annotation to make a few fields necessary and other ignorable.
You could try to put the DateTimeFormat annotation on you date fields, like this:
#DateTimeFormat(pattern = "dd/mm/yyyy") // put any pattern you want
private Date myDate;
Note: If you are using a version of Spring older than 3.2, you need to add joda date library to your project classpath

Spring-MVC bean Validation Type mismtach error

I am trying to validate an object using Spring JSR303 validation, i have a form object which have some nested objects along with some form properties here is my Form signature
public class PaymentDetailsForm
{
private AddressForm billingAddress;
// other properties and getter and setters
}
In my AddressForm bean i have used Bean validation annotations to validate data, but i am not using any #Valid annotation inside my PaymentDetailsForm for billingAddress.
This is the signature of my Controller method
public String createUpdatePaymentInfos(final Model model,
#ModelAttribute("paymentInfo") #Valid final PaymentDetailsForm form, final BindingResult bindingResult)
{
}
If i am sending correct data from the form everything is working perfectly fine, but if i omit any field from billingAddress which is marked as required or not null i am getting following binding error exception
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'paymentInfo' on field 'billingAddress':
rejected value [com.xxx.storefront.forms.AddressForm#e39f6f1,true];
codes [typeMismatch.paymentInfo.billingAddress,typeMismatch.billingAddress,typeMismatch.com.xxx.storefront.forms.AddressForm,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [paymentInfo.billingAddress,billingAddress]; arguments []; default message [billingAddress]];
default message [Failed to convert property value of type 'java.lang.String[]'
to required type 'com.xxx.storefront.forms.AddressForm' for property 'billingAddress';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String[]] to required type [com.xxx.storefront.forms.AddressForm] for property 'billingAddress':
no matching editors or conversion strategy found]
I was expecting that since i have not used #valid annotation for billingAddress property, it should not be validated but even in case it get validated i am not able to understand above mentioned exception/error
The bindingResult that you are seeing doesn't look like it is because of validation errors, it is likely because of the binding errors - not being able to bind the UI fields to the inner billingAddress field. Even the binding errors would end up showing in the immediately following bindingresult argument like you are seeing.
That was due to some wrong mapping from UI,in my JSP page i was mapping address fields to billingAddress object but there was one hidden field like
<form:hidden path="billingAddress" id="billingAddress"/>
This was the cause of error since it was trying to send String array and Spring binding was unable to distinguish what i am trying to do

org.springframework.expression-3.1.0.M2.jar has no source attachment

I am working on spring mvc 3.0 that integrated spring-social-facebook. When I debug the code, there is an error at line
List<Connection<?>> connections = connectionRepository.findConnections(providerId);
in the following method
#RequestMapping(value="/{providerId}", method=RequestMethod.GET)
public String connectionStatus(#PathVariable String providerId,
NativeWebRequest request,
Model model) {...}
and controller is ConnectController
Eclipse shows
Source not found
And when i keep the line inside try catch block, then error message is
Expression parsing failed; nested exception is
org.springframework.expression.spel.SpelEvaluationException:
EL1007E:(pos 22): Field or property 'name' cannot be found on null
I have added the org.springframework.expression-3.1.0.M2.jar file in WEB-INF/lib. I have also tried this using "Add External Jars..". Any help would be appreciated.

Spring MVC Data Binding Error

I'm getting the following error when I try to retrieve the form results in controller method:
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'search' on field 'clients': rejected value [14]; codes [typeMismatch.search.clients,typeMismatch.clients,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [search.clients,clients]; arguments []; default message [clients]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'clients'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.Client] for property 'clients[0]': no matching editors or conversion strategy found]
Model Object looks like this:
public class SearchForm {
private String name;
private List<Client> clients;
//getters and setters
}
public class Client {
private String name;
private Int id;
}
form:
<form:form method="POST", name="searchresults.html" modelattibute="search">
<form:input path="name"/>
<form:checkboxes path="clients" items="{clientsList}" itemsValue="id" itemsLabel="name"/>
</form:form>
this form displays the values correctly on the html page but when I click the submit button I get the above error
The browser will only send a list of client IDs when the form is submitted. How could Spring know how to convert each ID into a Client instance. You either have to tell it how to do, or add a List<String> clientIds property to your bean, and make the form:checkboxes tag use this property instead of clients as its path.

Resources