bean validation get parameter jsf - validation

Using bean validation like:
#Size(max = 5)
private String name;
How do I retrieve the max value to use within my JSF site? For example to set maxlength value in input text component.

Related

Set input field attribute in Thymeleaf from database

I have a table in the database with fields like below which holds my form input's attributes:
#Column(name = "propertyname")
private String propertyname;
#Column(name = "propertyvalue")
private String propertyvalue;
#Column(name = "propertytype")
private String propertytype;
#Column(name = "propertyrequired")
private String propertyrequired;
#Column(name = "propertysize")
private String propertysize;
#Column(name = "propertymin")
private String propertymin;
Now I am getting these as bean fields in Thymeleaf template. But keep getting template parsing error (on the same line as below). I am trying to achieve below:
<input th:field="${modelAttribute.beanPropertyList[__${rowStat.index}__].propertyname}" th:errorclass="is-invalid" th:required="${modelAttribute.beanPropertyList[__${rowStat.index}__].propertyrequired}" th:min="${modelAttribute.beanPropertyList[__${rowStat.index}__].propertymin}" th:max="${modelAttribute.beanPropertyList[__${rowStat.index}__].propertymax}"/>
What am I doing wrong? or what is the correct approach for this?
th:field doesn't work like that. It requires a th:object="${foo} as a form backing bean. Then th:field="*{bar}" will set the input's name="bar" and try to reflect on the model object called foo and get its field call bar to use the input's value
Try th:name and th:value separately. That also seems more plausible given your model.

Creating internationalized standard javax.validation error messages

I have a small requirement of writing standardized, internationalized javax.validation error messages in this format
#NotNull
private String name;
#Max(10)
private int age;
Then in this case the error message should prop up as
"The field name is not null"
"The field age is not greater than or equal to 10"
How can I achieve this in a more dynamic way instead of hard-coding the message or variable name inside the annotation.
#NotNull(message = "{errors.name.missing.msg}")
private String name;
define the value for errors.name.missing.msg in messages.properties (which should be available in your classpath)
You can also make it locale specific by placing it in locale specific property files say in messages_en.properties and messages_fr.properties for i18n.

How to get #value property from applicationContext

I am trying to get class fields with #value annotation and then fill it by applicationContext.
I am using spring framework.
myClzz.java:
#Value("#{T(java.time.Duration).parse('${interval:PT12H}')}")
private Duration interval;
myService.java:
Field field = FieldUtils.getFieldsWithAnnotation(myClzz.getClass(), Value.class);
//get "#{T(java.time.Duration).parse('${interval:PT12H}')}" from the field:
String value = field.getDeclaredAnnotations()....
String result = applicationContext.getEnvironment().getProperty(value)
application.properties:
interval=PT12H
But getProperty does not work with that "#{T(java.time.Duration).parse('${interval:PT12H}')}" string.
Is there any way to make it work without parsing?

Ignoring spring mvc JSR-303 validations for selective entity fields

I have spring4 mvc application to save an Address entity, code bit as follows.
My Controller
#RequestMapping(value = "addAddress", method = POST)
public String registerComplaint(#Valid #ModelAttribute final Address address, final BindingResult resultBinder) {
if (resultBinder.hasErrors())
return "addAddress";
addressService.addAddress(address);
return "redirect:myAddress";
}
My Entity
#Entity
#Table(name = "address")
public class Address {
#NotNull
private String street;
#NotNull
private String pin;
#NotNull
private String createdBy;
........
}
My form conatins only street and pin as field, where as createdBy should be set by me after validating the other form values.
Here the problem is spring JSR303 validation support is validating a field ie createdBy which i don't want to validate by spring mvc.
How can i instruct spring mvc not to validate these kind of optional fields while using #Valid annotation.
Is there any way i can skip fields like this using spring mvc ?
Validation is mainly for user input. Since you will be setting createdBy yourself, just do so before saving it (e.g #PrePersist), or have a new Date as a default value. If you need to enforce a constraint for createBy, you can do so at the schema level.
#Column(nullable=false, ...)
private String createdBy = new Date();
You need to read up on Validation Groups. This lets you use different validators depending on the "scenario"
Use Spring's #Validated annotation to use groups
If you don't protect the createdBy field, a user can change it by altering the POST variables. See DataBinder.setDisallowedFields()
Conceptually, how is a pin related to an address?
It sounds like you want to use a Form Backing Object here (a regular non-JPA POJO made just for a form), and copy values to your real entities.

Hibernate saves empty Spring autobound ojects

I'm using Spring + JSF2 + Hibernate to build a web application. Two relevant classes look like this:
#Entity
#Table(name="people")
#Named
public class Person implements Serializable {
private int id;
private String forename;
#Inject private PhoneNumber mobile_phone;
/* Other properties */
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="mobile_phone_number_id", nullable = true)
public PhoneNumber getMobilePhone() {
return mobile_phone;
}
/* Other getters and setters */
}
#Entity
#Table(name="phone_numbers")
#Named
public class PhoneNumber {
private Integer id;
private String code;
private String number;
/* Other stuff */
}
Dependency injection is handled by Spring (#Named, #Inject). Database persistence is configured through Hibernate annotations (#OneToOne, #JoinColumn). JSF form elements are bound to these classes using EL.
My question is how to tell hibernate no to save autobound PhoneNumber if all its fields are left blank (the user doesn't submit any values)? In other words, I want the Person object to be saved but don't want records with empty strings appear in the phone_numbers table.
And two bonus questions if someone knows.
When does Spring bind the PhoneNumber - at Person creation or when a request for a PhoneNumber comes from JSF?
[SOLVED] I have fields in my form which aren't marked with the required attribute in JSF. Obviously, if such fields are left empty, validation shouldn't be triggered. The problem is that when I configured Hibernate validator, such non-required fields are now validated even when left blank. Is there any way to skip validation for empty fields which aren't marked as required in JSF? I tried to set <prop key="javax.persistence.validation.mode">CALLBACK</prop> in hibernateProperties of SessionFactory bean, but this didn't help.
The second bonus question has the following answer: JSF treats empty fields as empty strings, so one must set
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
in web.xml to interpret empty strings as null. Obviously, an empty string didn't validate well against my regex validation pattern.

Resources