Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Bean Custom Validation for Mobile Apps – JSR-303 Annotations

DZone's Guide to

Spring Bean Custom Validation for Mobile Apps – JSR-303 Annotations

This article shows you how to perform Spring Bean custom validations for mobile apps with JSR-303 annotations.

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

This article shows you how to perform Spring Bean custom validations for mobile apps with JSR-303 annotations.

1. Below dependencies should be added to pom.xml to handle spring bean validations:

<!--Java validation jars -->
    <dependency>

        <groupId>javax.validation</groupId>

        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>

<!--Hibernate validation jars -->

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
</dependency>

2. Provide below hibernate validations to your DTO (in this example MyDTO. java):

public class MyDTO {

    @NotEmpty

    @Size(min = 1, max = 16)

    @Pattern(regexp = "[a-zA-Z0-9]+")

    private String name;

    @NotEmpty

    @Size(min = 1, max = 12)

    private String password;

}

3. messageSource definition should be provided to context.xml(src\main\webapp\WEB-INF\applicationContext.xml). This definition will intialize the messages.properties file:

<bean id="messageSource"     class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>messages</value>
            <value>displaytag</value>
        </list>
    </property>
</bean>

4. Below validation messages should be provided to messages.properties file:

4. Below validation messages should be provied to messages.properties file (src\main\resources\messages.properties) 

NotEmpty ={0} cannot be empty.
Size ={0} should be between {2} and {1} characters.
Pattern = The {0} must be a alphanumeric.

5. Add below definition to your controller to handle validation for DTO object (MyController.java):

import javax.validation.Valid;

@RestController
public class MyController {

    @RequestMapping(value = "/v1/sessions/login", method = RequestMethod.POST)
    public ResponseEntity<LoginDTO> login(@Valid @RequestBody MyDTO login)
    throws Exception {
        //code goes here

    }

}

6. Added below Exception handler to your controller advice (MyControllerAdvice.java):

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.mypackage.restservices.model.RestErrors;

import com.mypackage.restservices.model.Errors;

@ControllerAdvice
public class MyControllerAdvice {

    @Autowired
    private MessageSource messageSource;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseEntity<RestErrors>     handleValidationException(MethodArgumentNotValidException ex) {
        List<Errors> errors = new ArrayList<Errors>();
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            Errors error = new Errors();
            error.setDefaultMessage(messageSource.getMessage(fieldError, null));
            error.setCode(fieldError.getCode());
            errors.add(error);
        }
        RestErrors restErrors = new RestErrors("Validation Failed", errors);
        return new ResponseEntity<RestErrors>(restErrors, HttpStatus.BAD_REQUEST);
    }

}

7. RestErrors.java changes to display properly to the user:

package com.mypackage.restservices.model;
import java.util.List;
public class RestErrors {

    private String message;
    private List<Errors> errors;
    public RestErrors(String message) {
        this.message = message;
    }
    public RestErrors(String message, List<Errors> errors) {
        this.message = message;
        this.errors = errors;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setErrors(List<Errors> errors) {
        this.errors = errors;
    }
    public List<Errors> getErrors() {
        return errors;
    }
}

8. Errors.java changes to store error code and default message to be displayed in the UI:

package com.mypackage.restservices.model;

public class Errors {
    private String code;
    private String defaultMessage;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getDefaultMessage() {
        return defaultMessage;
    }
    public void setDefaultMessage(String defaultMessage) {
        this.defaultMessage = defaultMessage;
    }

}

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
bean validation api support ,mobile app ,spring validation

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}