验证不在Spring控制器中执行

时间:2018-04-10 12:24:38

标签: java spring spring-boot

我想在课堂上使用注释。我使用javax.validation.constrants.*进行注释。

public final class EmailCredential implements Serializable {

    private static final long serialVersionUID = -1246534146345274432L;

    @NotBlank(message = "Sender must not be empty.")
    @Email
    private final String sender;

    @NotBlank(message = "Subject must not be empty.")
    private final String subject;

/// getters setters

}

他们都没有按预期工作。这意味着当调用下面的API时,如果带注释的字段无效,则注释应该抛出错误。看起来没有注释来检查字段。我在正常班级中如何正确使用注释?

控制器:

@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }

2 个答案:

答案 0 :(得分:2)

根据Spring Boot官方文档:Validating Form Input

您应该指明需要使用注释EmailCredential

验证您的@Valid

以下是文档中的示例:

package hello;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Controller
public class WebController implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/")
    public String showForm(PersonForm personForm) {
        return "form";
    }

    @PostMapping("/")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/results";
    }
}

答案 1 :(得分:2)

在您的情况下,必须指定验证被触发 因此,在要验证的参数上添加@Valid注释,例如:

import javax.validation.Valid;
// ...
@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody @Valid EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }