How can to set validation (org.hibernate.validator.constraints) for rest in spring boot project? -
i have project spring boot, spring mvc , hibarnate, , want validate rest params, have controller:
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 params login = " + login + ", password = " + password + ", email = " + email); return !userservice.findbyloginandpassword(login, password) && userservice.adduser(new user(login, password, email)); } }
and 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" }
so, wrote registration user, , added validation (@notempty login , password, @email) rest params, validation not performed :(, send request invalid param password="" , request runs without errors :(, why? set validation @notempty password , if set password="" or null must see error! becouse set validation. me, please.
validation not performed on method parameters. move pojo annotate @valid
, @modelattributes
, you'll fine.
something like
@requestmapping(value = "/registration", method = requestmethod.post) public @responsebody boolean registration(@valid foobar foobar) { } static class foobar { @notempty string login; @notempty string password; @email(canbenullorempty = true) string email; // getter & setter }
Comments
Post a Comment