복붙노트

[SPRING] Spring MVC의 유효성 검사

SPRING

Spring MVC의 유효성 검사

유효성 검사기 클래스에서 요청 개체를 가져 오는 방법. 요청 개체에있는 매개 변수 즉 내용을 확인해야합니다.

해결법

  1. ==============================

    1.100 % 확신 할 수는 없지만 Spring MVC를 사용하면 메소드를 객체에 전달하고 (적어도 Spring 3에서는) 주석을 달아줍니다.

    100 % 확신 할 수는 없지만 Spring MVC를 사용하면 메소드를 객체에 전달하고 (적어도 Spring 3에서는) 주석을 달아줍니다.

    @RequestMethod(value = "/accounts/new", method = RequestMethod.POST)
    public String postAccount(@ModelAttribute @Valid Account account, BindingResult result) {
        if (result.hasErrors()) {
            return "accounts/accountForm";
        }
    
        accountDao.save(account);
    }
    

    관련 주석은 JSR-303의 일부인 @Valid입니다. 위에서 설명한 것처럼 BindingResult 매개 변수도 포함 시켜서 오류를 검사 할 수있는 방법이 있습니다.

  2. ==============================

    2.두 가지 선택이 있습니다.

    두 가지 선택이 있습니다.

    JSR 303의 경우 Spring 3.0이 필요하며 Model 클래스에 JSR 303 Annotations로 주석을 추가하고 웹 컨트롤러 처리기 메서드에서 @Valid를 사용자 앞에 지정해야합니다. (그의 대답에서 Willie Wheeler 쇼와 같이). 또한 구성에서이 기능을 활성화해야합니다.

    <!-- JSR-303 support will be detected on classpath and enabled automatically -->
    <mvc:annotation-driven/>
    

    Spring Validator의 경우, org.springframework.validation.Validator 인터페이스를 구현하는 Validator (Jigar Joshi의 대답 참조)를 작성해야한다. 검사기를 컨트롤러에 등록해야합니다. Spring 3.0에서는 @InitBinder annotated 메소드에서 WebDataBinder.setValidator (setValidator)를 사용하여이를 수행 할 수있다 (setValidator는 수퍼 클래스 DataBinder의 메소드이다)

    Example (from the spring docu)
    @Controller
    public class MyController {
    
        @InitBinder
        protected void initBinder(WebDataBinder binder) {
            binder.setValidator(new FooValidator());
        }
    
        @RequestMapping("/foo", method=RequestMethod.POST)
        public void processFoo(@Valid Foo foo) { ... }
    }
    

    더 자세한 내용은 Spring 레퍼런스, 5.7.4 Spring MVC 3 Validation을 보라.

    BTW : Spring 2에는 SimpleFormController에 setValidator 속성과 같은 것이 있습니다.

  3. ==============================

    3.간단한 검사기 (사용자 정의 검사기) Validator에는 param을 얻기위한 요청 객체가 필요하지 않습니다. 당신은 직접 가져올 수 있습니다.

    간단한 검사기 (사용자 정의 검사기) Validator에는 param을 얻기위한 요청 객체가 필요하지 않습니다. 당신은 직접 가져올 수 있습니다.

    예를 들면 다음과 같습니다. 요청의 필드를 이름과 나이로 검사합니다.

    public class PersonValidator implements Validator {
    
        /**
        * This Validator validates just Person instances
        */
        public boolean supports(Class clazz) {
            return Person.class.equals(clazz);
        }
    
        public void validate(Object obj, Errors e) {
            ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
            Person p = (Person) obj;
            if (p.getAge() < 0) {
                e.rejectValue("age", "negativevalue");
            } else if (p.getAge() > 110) {
                e.rejectValue("age", "too.darn.old");
            }
        }
    }
    

    참조

  4. ==============================

    4.HttpServletRequest 매개 변수를 사용하여 다른 메서드를 쉽게 추가 할 수 있습니다.

    HttpServletRequest 매개 변수를 사용하여 다른 메서드를 쉽게 추가 할 수 있습니다.

     public void validateReq(Object target, Errors errors,HttpServletRequest request) {
    
           // do your validation here
    }
    

    여기서 메서드를 재정의하지 않습니다.

  5. ==============================

    5.또한 스프링 밸리데이터가 captcha의 유효성을 검사 할 때도 동일한 문제가 발생합니다. validator implementor에서 HttpSession (HttpServletRequest get HttpSession)에서 correct-captcha를 얻고 싶습니다.

    또한 스프링 밸리데이터가 captcha의 유효성을 검사 할 때도 동일한 문제가 발생합니다. validator implementor에서 HttpSession (HttpServletRequest get HttpSession)에서 correct-captcha를 얻고 싶습니다.

    유효성 검사기에서 얻을 수있는 좋은 코드가 없습니다.

    다음과 같이 몇 가지 타협안이 있습니다.

  6. from https://stackoverflow.com/questions/5576790/validation-in-spring-mvc by cc-by-sa and MIT license