2016년 12월 25일 일요일

Spring Request Body Validation

You can check request body validation by using hibernate validator.

first of all, you can add the validation annotation to your request body class.

package org.blog.test.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ValidationRequest implements Serializable {

    private static final long serialVersionUID = 2207905388150465893L;

    @Size(max = 2)
    private String numRange;

    @Email
    private String email;

}


@Size annotation checks string's length. If numRange's string length is over 2, it shows exception.
@Email annotation checks String's format whether it follows email format.

And then, you can add the @valid annotation to your controller class's request body part.

package org.blog.test.controller;

import org.blog.test.model.ValidationRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class ValidationController {

    @RequestMapping(method = RequestMethod.POST, path = "/validate")
    public String checkValidation(@Valid @RequestBody ValidationRequest validationRequest) {
        return "success";
    }
}

Now, you can find the error message when you don't keep the constraint.

{
  "timestamp": 1482679824788,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Email.validationRequest.email",
        "Email.email",
        "Email.java.lang.String",
        "Email"
      ],
      "arguments": [
        {
          "codes": [
            "validationRequest.email",
            "email"
          ],
          "arguments": null,
          "defaultMessage": "email",
          "code": "email"
        },
        [],
        {
          "defaultMessage": ".*",
          "codes": [
            ".*"
          ],
          "arguments": null
        }
      ],
      "defaultMessage": "이메일 주소가 유효하지 않습니다.",
      "objectName": "validationRequest",
      "field": "email",
      "rejectedValue": "test",
      "bindingFailure": false,
      "code": "Email"
    }
  ],
  "message": "Validation failed for object='validationRequest'. Error count: 1",
  "path": "/validate"
}

댓글 없음 :

댓글 쓰기