zoukankan      html  css  js  c++  java
  • 在Spring MVC中使用注解的方式校验RequestParams

    概述

      Spring MVC支持Bean Validation,通过这个验证技术,可以通过注解方式,很方便的对输入参数进行验证,之前使用的校验方式,都是基于Bean对象的,但是在@RequestParam中,没有Bean对象,这样使得校验无法进行,可以通过使用@Validated注解,使得校验可以进行。

    校验bean对象

      一般校验bean对象,为了可以自动的校验属性,可以通过两步解决:

    一、声明对象

    package com.github.yongzhizhan.draftbox.model;
    
    import javax.validation.constraints.Size;
    
    /**
     * 带验证的对象
     * @author zhanyongzhi
     */
    public class Foo {
        private String validString;
    
        @Size(min = 1, max = 5)
        public String getValidString() {
            return validString;
        }
    
        public void setValidString(final String vValidString) {
            validString = vValidString;
        }
    }

    二、通过@Valid注解使用对象

    @ResponseBody
    @RequestMapping(value = "validObject", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public String validObject(
            @RequestBody()
            @Valid Foo vFoo, BindingResult vBindingResult){
    
        return vFoo.getValidString();
    }

    校验RequestParams

      使用校验bean的方式,没有办法校验RequestParam的内容,一般在处理Get请求的时候,会使用下面这样的代码:

    @ResponseBody
    @RequestMapping(value = "validString", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public String validString(
            @RequestParam(value = "str", defaultValue = "")
            String vStr){
    
        return vStr;
    }

      使用@Valid注解,对RequestParam对应的参数进行注解,是无效的,需要使用@Validated注解来使得验证生效。操作步骤如下:

    一、声明错误处理类

    package com.github.yongzhizhan.draftbox.controller;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Component;
    import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    import javax.validation.ValidationException;
    
    @ControllerAdvice
    @Component
    public class GlobalExceptionHandler {
        @Bean
        public MethodValidationPostProcessor methodValidationPostProcessor() {
            return new MethodValidationPostProcessor();
        }
    
        @ExceptionHandler
        @ResponseBody
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        public String handle(ValidationException exception) {
            System.out.println("bad request, " + exception.getMessage());
            return "bad request, " + exception.getMessage();
        }
    }

    二、声明@Validated并加上校验注解

    package com.github.yongzhizhan.draftbox.controller;
    
    import com.github.yongzhizhan.draftbox.model.Foo;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.HttpStatus;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    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.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.validation.Valid;
    import javax.validation.constraints.Size;
    
    @RestController
    @SuppressWarnings("UnusedDeclaration")
    @Validated
    public class IndexController {
        @ResponseBody
        @RequestMapping(value = "validString", method = RequestMethod.GET)
        @ResponseStatus(HttpStatus.OK)
        public String validString(
                @RequestParam(value = "str", defaultValue = "")
                @Size(min = 1, max = 3)
                String vStr){
    
            return vStr;
        }
    }

    代码

    在github中查看完整代码

    参考

    Bean Validation 技术规范特性概述
    Validation, Data Binding, and Type Conversion

  • 相关阅读:
    Two strings CodeForces
    Dasha and Photos CodeForces
    Largest Beautiful Number CodeForces
    Timetable CodeForces
    Financiers Game CodeForces
    AC日记——整理药名 openjudge 1.7 15
    AC日记——大小写字母互换 openjudge 1.7 14
    AC日记——将字符串中的小写字母换成大写字母 openjudge 1.7 13
    AC日记——加密的病历单 openjudge 1.7 12
    AC日记——潜伏着 openjudge 1.7 11
  • 原文地址:https://www.cnblogs.com/itrena/p/8967866.html
Copyright © 2011-2022 走看看