0
我和春天有個開機,Spring MVC和hibarnate的項目,我想驗證其餘參數,可以我有控制器:如何設置驗證(org.hibernate.validator.constraints)在spring引導項目中休息?
import domain.User;
import service.UserService;
import validate.Email;
import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.ws.rs.FormParam;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public @ResponseBody Boolean registration(@NotEmpty @FormParam("login") String login,
@NotEmpty @FormParam("password") String password,
@Email(canBeNullOrEmpty = true) @FormParam("email") String email) {
logger.debug("method registration with params login = " + login
+ ", password = " + password + ", email = " + email);
return !userService.findByLoginAndPassword(login, password)
&& userService.addUser(new User(login, password, email));
}
}
和我的build.gradle:
apply plugin: 'war'
apply plugin: 'spring-boot'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE")
}
}
ext {
springVersion = '4.1.5.RELEASE'
jacksonVersion = '2.5.3'
}
sourceCompatibility = 1.5
repositories {
mavenCentral()
}
dependencies {
compile 'javax.validation:validation-api:1.1.0.Final'
compile "org.hibernate:hibernate-validator:5.1.3.Final"
compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion"
compile 'javax.ws.rs:javax.ws.rs-api:2.0.1'
compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
compile "com.fasterxml.jackson.core:jackson-core:$jacksonVersion"
compile "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion"
compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
}
所以,我寫了登記爲我的用戶,並添加驗證(@NotEmpty登錄和密碼,@電子郵件)爲rest params,但驗證不執行:(我發送請求與無效的參數密碼=「」和請求運行沒有錯誤:(爲什麼?我爲密碼設置了驗證@NotEmpty,如果我設置了密碼=「」或null,我必須看到錯誤!becouse設置驗證。請幫助我。
是否只是標註的參數'@ Valid'不行的,而不是參數移動到一個POJO?只是爲了證實,因爲我覺得匆匆回憶起我們曾經在某個項目中使用過@Valid。 – Sanjay
當然你可以在方法參數中加上'@ Valid'(這就是觸發驗證的原因!)。但是你不能對方法參數施加約束(所以你不能把'@ NotNull'作爲例子)。我會編輯我的答案,使其更清楚。 –
也許我錯誤地回想起對方法參數施加約束。 – Sanjay