I know that I could put the annotations on age field.
But I want to validate age in setAge method, here is my code:
class UserController {
#PutMapping
public ResponseEntity partialUpdate(#RequestBody #Validated UserDTO userDTO) {
return userService.partialUpdate(userDTO);
}
}
public class UserDTO {
private String username;
private Integer age;
public void setAge(#Min(0) #Max(100) Integer age) {
this.age = age;
}
}
It's valid when I give age=101, seems the validations not work.
Seems like you need to use the Validator to check whether you class is valid.
If you are creating a object of UserDTO.
UserDTO user = new UserDTO("My Name", 101);
Then perform the following
Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
Set<ConstraintViolation<SomeEntity>> errors = validator.validate(user);
Then based on your requirement do the necessary things like notify client what was the wrong field, log them. If empty then it seems like everything is valid and proceed further.
if(CollectionUtils.isNotEmpty(errors)){
throw new ConstraintViolationException(errors);
}
Related
For example I have:
#PostMapping("/person/{id}")
#ResponseBody
public boolean isAdmin(#PathVariable("id") Person person) {
return person != null && person.isAdmin();
}
How I can get same result using Validation?
This not works for me, but I look up for something like this, without manual checking in method body. Is there way for doing so?
#PostMapping("/person/{id}")
#ResponseBody
public boolean isAdmin(#PathVariable("id") #NotNull Person person) {
return person.isAdmin();
}
you need to use javax.validation.Valid and add constraints to your Person pojo: javax.validation.constraints.Email/NotBlank/NotNull;
public class Person {
#NotNull
private Long id;
/* here getters and setters...*/
}
In your controller:
#PostMapping("/person/{id}")
#ResponseBody
public boolean isAdmin(#Valid #RequestBody Person person) {
return person.isAdmin();
}
see my github
I'm using hibernate validations for validating incoming requests in spring #RestController.
Problem: I want to reuse the same DTO object in multiple endpoints. But validate some fields only by condition (eg only on specific endpoints).
#RestController
public class ProductsServlet {
#GetMapping("/avail/product")
public Object avail(#Valid ProductDTO product) {
//should validate id field only
}
#GetMapping("/sell/product")
public Object sell(#Valid(with = GroupFuture.class) ProductDTO product) {
//should validate id + from field
}
}
public class ProductDTO {
#NotNull
#NotBlank
private String id;
#Future(groups = GroupFuture.class)
private Date from;
}
Of course the #Valid(with = GroupFuture.class) statement is invalid. But it shows what I'm trying to achieve.
Is that possible?
Got it. Also having to use the Default.class group to validate any fields not having a group.
#GetMapping("/sell/product")
public Object sell(#Validated({Default.class, GroupFuture.class}) ProductDTO product) {
}
My ModelClass
public class UserPojo{
private String userEmailId;
private String userPassword;
private String userContactNumber;
//setters and getters
}
I want to send UserPojo class object as json but In somecases I want to send with userpassword and somecases without userpassword is it possible?
In below method I want to send userPojo object without userpassword.
My Spring version is 4.3.1.RELEASE. I have Jackson libraries
#RestController
#RequestMapping("/user")
public class UserController{
#GetMapping(value="/{userId}")
public UserPojo getUser(#PathVariable("userId") String userId){
//code goes here
//finally returning UserPojo Object
return userPojo;
}
}
In below method I want to send userPojo object with password
#RestController
#RequestMapping("/admin")
public class AdminController{
#GetMapping(value="/{userId}")
public UserPojo getUser(#PathVariable("userId") String userId){
//code goes here
//finally returning UserPojo Object
return userPojo;
}
}
I hope you got my point
For your requirement use #JsonView, if you want to ignore totally some field then #JsonIgnore.
Yes, this is achieved by using #JsonView annotation.
Here is a nice tutorial how to use this feature
You can add this annotation at the field level and that attribute will be excluded from the JSON response.
#JsonProperty(access = Access.WRITE_ONLY)
private float height;
I am running the service under TomEE.
The model is very simple:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Card {
#XmlElement(required = true, nillable = false)
private String cardNumber;
public Card() {
//no-op
}
public Card(final String s) {
cardNumber = s;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
I followed this example
https://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced008.htm
The service is also very simple like:
#Consumes(APPLICATION_XML)
#Produces(APPLICATION_XML)
public class MyService {
#POST
#Path("status")
public String queryStatus(Card card) {
// do something
}
}
If my input is wrongly formatted, it will have a proper exception. But it doesn't seem to be able to validate empty card number or null.
For example, when I have
"<card></card>"
or
"<card><cardNumber> </cardNumber></card>"
(with an empty string), the service still goes through, with the "cardNumber" property being null or empty.
Well, I could do something in the setter to throw out an exception. But I was hoping JavaEE automatically handle this kind of this if I put the annotation on the property.
So what am I missing here?
Thank you for any tips!
With Bean Validation (http://beanvalidation.org/) Java EE offers a standard way to validate objects. It is also integrated with JAX RS.
So you can use annotations like #NotNull in your Card class. In your Service just say that you want a #Valid Card.
An example can be found here: https://jaxenter.com/integrating-bean-validation-with-jax-rs-2-106887.html
class employee{
...
private long phone;
...
}
I want to validate phone number using spring jsr303 validator, In my Controller I am using #valid. I am successfully validating entered value is number or string by using generic typeMismatch placing in error message property file.
But I want to validate entered number format is correct or not.(#pattern for string only)
How to achieve this one,please suggest me.
Normally phone numbers are String and you can validate by using #Pattern, but if you want to validate any fields you can do like this.
Custom annotation Javax validator
#javax.validation.Constraint(validatedBy = { PhoneNumberConstraintValidator.class })
#Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Retention(RUNTIME)
public #interface ValidPhoneNumber {
}
public class PhoneNumberConstraintValidator implements ConstraintValidator<ValidPhoneNumber, Long> {
#Override
public void initialize(final ValidPhoneNumber constraintAnnotation) {
// nop
}
#Override
public boolean isValid(final Long value, final ConstraintValidatorContext context) {
//your custom validation logic
}
}
class employee{
...
private long phone;
#ValidPhoneNumber
public Long getPhone() { return phone; }
...
}
OR simpler if you have hibernate validator, you can just add this method in your entity class.
#org.hibernate.validator.AssertTrue
public boolean validatePhoneNumber() { }