简体   繁体   English

使用Javax.validation的Spring验证将重定向到400

[英]Spring validation with Javax.validation redirects to 400

I am working on a Spring-MVC application, and I want to validate some data. 我正在开发Spring-MVC应用程序,我想验证一些数据。 Currently I am able to validate the data with no problems. 目前,我能够毫无问题地验证数据。 Only thing is if the data is invalid, I would like to go to another JSP page, which is not happening right now. 唯一的是,如果数据无效,我想转到另一个JSP页面,该页面目前没有发生。 Instead I get an Apache 400 error, request was sent syntactically incorrect. 相反,我收到一个Apache 400错误,语法上发送的请求不正确。 Can anyone tell me what all is remaining to implement in validation. 谁能告诉我在验证中还剩下什么呢?

Controller : 控制器:

@RequestMapping(value = "/", method = RequestMethod.GET)
    public String listPersons(Model model) {
        Person person = personService.getCurrentlyAuthenticatedUser();
        if(!(person==null)){
            return "redirect:/canvas/list";
        } else {
            model.addAttribute("person", new Person());
         //   model.addAttribute("listPersons", this.personService.listPersons());
            model.addAttribute("notices",new Notes());
            model.addAttribute("canvases",new Canvas());
            return "person";
        }
    }

    @RequestMapping(value= "/person/add", method = RequestMethod.POST)
    public String addPerson(@Valid Person person,@ModelAttribute("person") Person p,Model model,BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            return "redirect:/";
        }
            this.personService.addPerson(p);
            return "redirect:/";

    }

Entity : 实体 :

@Entity
@Table(name="person")
public class Person implements UserDetails{

    @NotEmpty @Email
    @Column(name = "username")
    private String username;

    @NotEmpty(message = "Please enter password")
    @Column(name = "password")
    private String password;

    @Size(min = 2,max = 30)
    @Column(name = "firstname")
    private String firstName;

    @Size(min = 2,max = 50)
    @Column(name = "secretquestion")
    private String secretquestion;


    @Size(min = 2,max = 500)
    @Column(name = "secretanswer")
    private String secretanswer;
}

JSP : JSP:

<tr>
    <td>
        <form:label path="firstName">
            <spring:message text="FirstName"/>
        </form:label>
    </td>
    <td>
        <form:input path="firstName" />
    </td>
    <td><form:errors path="firstName"/>Please enter Firstname properly</td>
</tr>
<tr>
    <td>
        <form:label path="username">
            <spring:message text="Email"/>
        </form:label>
    </td>
    <td>
        <form:input path="username" />
    </td>
    <td><form:errors path="username"/>Please enter Email properly</td>
</tr>
<tr>
    <td>
        <form:label path="password">
            <spring:message text="Password"/>
        </form:label>
    </td>
    <td>
        <form:input path="password" />
    </td>
    <td><form:errors path="password"/>Please enter password properly</td>
</tr>

<tr>
<td>
    <form:label path="secretquestion">
        <spring:message text="secretquestion"/>
    </form:label>
</td>
<td>
    <form:input path="secretquestion" />
</td>
    <td><form:errors path="secretquestion"/>Please enter secretquestion properly</td>
</tr>


<tr>
    <td>
        <form:label path="secretanswer">
            <spring:message text="secretanswer"/>
        </form:label>
    </td>
    <td>
        <form:input path="secretanswer" />
    </td>
    <td><form:errors path="secretanswer"/>Please enter secretanswer properly</td>
</tr>

Servlet-context.xml Servlet-context.xml

 <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"/>

Pom.xml Pom.xml

<!-- Validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

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

Any pointers would be nice. 任何指针都很好。 Mainly I would like to avoid going on Apache 400, but just display what exactly went wrong with the input field. 主要是我想避免使用Apache 400,而只显示输入字段到底出了什么问题。

This is might be because of public String addPerson(@Valid Person person,@ModelAttribute("person") Person p,Model model,BindingResult bindingResult) signature . 这可能是由于public String addPerson(@Valid Person person,@ModelAttribute("person") Person p,Model model,BindingResult bindingResult)签名引起的。
BindingResult must follow @ModelAttribute as method signature might have more that one model object and Spring will create a separate BindingResult instance for each of them.That is why when the data is invalid spring is not able to bind errors to BindingResult and throws 400 error. BindingResult必须遵循@ModelAttribute因为方法签名可能具有多个模型对象,并且Spring将为每个模型对象创建一个单独的BindingResult实例,这就是为什么当数据无效时spring不能将错误绑定到BindingResult并引发400错误。

Try changing method signature to public String addPerson(@Valid Person person,@ModelAttribute("person") Person p,BindingResult bindingResult,Model model) . 尝试将方法签名更改为public String addPerson(@Valid Person person,@ModelAttribute("person") Person p,BindingResult bindingResult,Model model)

Read more on BindingResult . 阅读更多关于BindingResult的信息

javax.validation 2.0.1 列表<object>不能在 spring 引导中工作<div id="text_translate"><p>我是新的 spring 引导开发。 我正在尝试通过从@RequestBody 传递列表来验证发布请求。 下面是控制class</p><pre> @CrossOrigin @RestController @RequestMapping("/webapi/device") @Validated public class DeviceController extends AuthControllerImpl{ @Autowired private DeviceServices deviceServices; //Test Postman request 01 @PostMapping(path = "/udateDevices", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) public ResponseEntity&lt;Object&gt; updateDeviceToDB( @RequestBody List&lt;@Valid Device&gt; device, @RequestParam("token") String token, Errors errors) { if (errors.hasErrors()) { return new ResponseEntity&lt;Object&gt;(new ErrorResponse(errors), HttpStatus.BAD_REQUEST); } if(isValidToken(token).= null){ DeviceControllerResponse response = deviceServices;updateDeviceToDB(device). if (,response.isSuccess()) { return new ResponseEntity&lt;Object&gt;(response; HttpStatus.BAD_REQUEST); } return ResponseEntity.ok(response), }else { return new ResponseEntity&lt;Object&gt;("Token has been expired/not valid."; HttpStatus.UNAUTHORIZED); } } }</pre><p> 下面是我的实体 class。</p><pre> import javax.validation.constraints.NotEmpty; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "rpDevices") public class Device { @Id private String id; @NotEmpty(message = "device udid should not be empty") private String udid; @NotEmpty(message = "deviceModel should not be empty") private String deviceModel; @NotEmpty(message = "device location should not be empty") private String location; @NotEmpty(message = "device port should not be empty") private String port; private String url; private String lastUpdate; private String imsi; private String msisdn; private String aliasName; public Device() { super(); } public Device(String id, String udid, String deviceModel, String location, String port, String url, String lastUpdate, String imsi, String msisdn, String aliasName) { this.id = id; this.udid = udid; this.deviceModel = deviceModel; this.location = location; this.port = port; this.url = url; this.lastUpdate = lastUpdate; this.imsi = imsi; this.msisdn = msisdn; this.aliasName = aliasName; } //Getter and setters }</pre><p> 它从不验证实体并给出以下错误。</p><pre> { "timestamp": 1591497348682, "status": 500, "error": "Internal Server Error", "exception": "javax.validation.UnexpectedTypeException", "message": "HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'updateDeviceToDB.device[0].port'", "path": "/xxxx/webapi/device/udateDevices" }</pre><p> 有人可以帮助如何直接从请求日验证列表。 <a href="https://www.baeldung.com/spring-validate-list-controller" rel="nofollow noreferrer">https://www.baeldung.com/spring-validate-list-controller</a>我试过这个但没有帮助。</p><p> 这是 pom 依赖项</p><pre> &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.21.RELEASE&lt;/version&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;dependencies&gt; &lt;.-- Adding spring boot cap --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework,restdocs&lt;/groupId&gt; &lt;artifactId&gt;spring-restdocs-mockmvc&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;.-- Adding spring boot security.ldap --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.ldap&lt;/groupId&gt; &lt;artifactId&gt;spring-ldap-core&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org:springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-ldap&lt;/artifactId&gt; &lt;/dependency&gt; &lt;.-- https.//mvnrepository.com/artifact/io.jsonwebtoken/jjwt --&gt; &lt;dependency&gt; &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt; &lt;artifactId&gt;jjwt&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;.-- starter-data-mongodb MongoRepository --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt; &lt;/dependency&gt; &lt;.-- javax.mail --&gt; &lt;dependency&gt; &lt;groupId&gt;com:sun.mail&lt;/groupId&gt; &lt;artifactId&gt;javax.mail&lt;/artifactId&gt; &lt;version&gt;1.5.5&lt;/version&gt; &lt;/dependency&gt; &lt;.-- https.//mvnrepository.com/artifact/javax.validation/validation-api --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.validation&lt;/groupId&gt; &lt;artifactId&gt;validation-api&lt;/artifactId&gt; &lt;version&gt;2.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- some other stuff related to testing -- &gt; &lt;/dependencies&gt;</pre></div></object> - javax.validation 2.0.1 List<Object> not working in spring boot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring javax.validation 问题 - Spring javax.validation problem Spring javax.validation批注未在BindingResult中捕获 - Spring javax.validation annotation not caught in BindingResult 使用 javax.validation 进行自定义验证 - Custom validation with javax.validation Javax.validation 抛出 InternerServerError 500 而不是 BadRequest 400 - Javax.validation throwing InternerServerError 500 instead of BadRequest 400 javax.validation和组合注释 - javax.validation and composed annoations javax.validation 2.0.1 列表<object>不能在 spring 引导中工作<div id="text_translate"><p>我是新的 spring 引导开发。 我正在尝试通过从@RequestBody 传递列表来验证发布请求。 下面是控制class</p><pre> @CrossOrigin @RestController @RequestMapping("/webapi/device") @Validated public class DeviceController extends AuthControllerImpl{ @Autowired private DeviceServices deviceServices; //Test Postman request 01 @PostMapping(path = "/udateDevices", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) public ResponseEntity&lt;Object&gt; updateDeviceToDB( @RequestBody List&lt;@Valid Device&gt; device, @RequestParam("token") String token, Errors errors) { if (errors.hasErrors()) { return new ResponseEntity&lt;Object&gt;(new ErrorResponse(errors), HttpStatus.BAD_REQUEST); } if(isValidToken(token).= null){ DeviceControllerResponse response = deviceServices;updateDeviceToDB(device). if (,response.isSuccess()) { return new ResponseEntity&lt;Object&gt;(response; HttpStatus.BAD_REQUEST); } return ResponseEntity.ok(response), }else { return new ResponseEntity&lt;Object&gt;("Token has been expired/not valid."; HttpStatus.UNAUTHORIZED); } } }</pre><p> 下面是我的实体 class。</p><pre> import javax.validation.constraints.NotEmpty; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "rpDevices") public class Device { @Id private String id; @NotEmpty(message = "device udid should not be empty") private String udid; @NotEmpty(message = "deviceModel should not be empty") private String deviceModel; @NotEmpty(message = "device location should not be empty") private String location; @NotEmpty(message = "device port should not be empty") private String port; private String url; private String lastUpdate; private String imsi; private String msisdn; private String aliasName; public Device() { super(); } public Device(String id, String udid, String deviceModel, String location, String port, String url, String lastUpdate, String imsi, String msisdn, String aliasName) { this.id = id; this.udid = udid; this.deviceModel = deviceModel; this.location = location; this.port = port; this.url = url; this.lastUpdate = lastUpdate; this.imsi = imsi; this.msisdn = msisdn; this.aliasName = aliasName; } //Getter and setters }</pre><p> 它从不验证实体并给出以下错误。</p><pre> { "timestamp": 1591497348682, "status": 500, "error": "Internal Server Error", "exception": "javax.validation.UnexpectedTypeException", "message": "HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'updateDeviceToDB.device[0].port'", "path": "/xxxx/webapi/device/udateDevices" }</pre><p> 有人可以帮助如何直接从请求日验证列表。 <a href="https://www.baeldung.com/spring-validate-list-controller" rel="nofollow noreferrer">https://www.baeldung.com/spring-validate-list-controller</a>我试过这个但没有帮助。</p><p> 这是 pom 依赖项</p><pre> &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.21.RELEASE&lt;/version&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;dependencies&gt; &lt;.-- Adding spring boot cap --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework,restdocs&lt;/groupId&gt; &lt;artifactId&gt;spring-restdocs-mockmvc&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;.-- Adding spring boot security.ldap --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.ldap&lt;/groupId&gt; &lt;artifactId&gt;spring-ldap-core&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org:springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-ldap&lt;/artifactId&gt; &lt;/dependency&gt; &lt;.-- https.//mvnrepository.com/artifact/io.jsonwebtoken/jjwt --&gt; &lt;dependency&gt; &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt; &lt;artifactId&gt;jjwt&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;.-- starter-data-mongodb MongoRepository --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt; &lt;/dependency&gt; &lt;.-- javax.mail --&gt; &lt;dependency&gt; &lt;groupId&gt;com:sun.mail&lt;/groupId&gt; &lt;artifactId&gt;javax.mail&lt;/artifactId&gt; &lt;version&gt;1.5.5&lt;/version&gt; &lt;/dependency&gt; &lt;.-- https.//mvnrepository.com/artifact/javax.validation/validation-api --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.validation&lt;/groupId&gt; &lt;artifactId&gt;validation-api&lt;/artifactId&gt; &lt;version&gt;2.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- some other stuff related to testing -- &gt; &lt;/dependencies&gt;</pre></div></object> - javax.validation 2.0.1 List<Object> not working in spring boot 在Spring 4 MVC中如何使用javax.validation和JSON请求? - How to use javax.validation and JSON request in Spring 4 MVC? VSCode,Gradle,Spring 启动,无法导入 javax.validation - VSCode, Gradle, Spring Boot, Can't import javax.validation JSR 303-javax.validation-验证日期 - JSR 303 - javax.validation - Validate a date javax.validation如何针​​对不同的语言环境? - javax.validation how to target different locale?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM