복붙노트

[SPRING] Spring 3 MVC : 사용자 정의 유효성 검사기로 유효성 검사 메시지 표시

SPRING

Spring 3 MVC : 사용자 정의 유효성 검사기로 유효성 검사 메시지 표시

도움이 필요해. 나는 jsp, MVC에서 초급입니다. Spring 3 MVC에서 사용자 정의 유효성 검사기로 양식 입력의 유효성을 검사하고 싶습니다.

내 유효성 검사기 클래스

   package validators;

import models.UserModel;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class UserValidator implements Validator {

   @Override
   public boolean supports(Class clazz) {
      return UserModel.class.isAssignableFrom(clazz);
   }

   @Override
   public void validate(Object target, Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "Enter firstname.");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "Enter surname.");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "Enter login.");

   }

}

컨트롤러 클래스

package controllers;

import java.util.ArrayList;
import models.UserModel;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import validators.UserValidator;
import database.UserDB;


@Controller
public class UserController {

@RequestMapping(value="pouzivatel/new", method=RequestMethod.POST)
   public ModelAndView newUser(@ModelAttribute UserModel user, BindingResult result){
      UserValidator validator = new UserValidator();
      validator.validate(user, result);
      if(result.hasErrors()){
         return new ModelAndView("/user/new","command",user);

      }
      ...
}

사용자를위한 모델

package models;

public class UserModel  {
   private String firstname="";
   private String surname="";

   public String getFirstname() {
      return firstname;
   }
   public String getSurname() {
      return surname;
   }

   public void setFirstname(String firstname) {
      this.firstname = firstname;
   }
   public void setSurname(String surname) {
      this.surname = surname;
   }

}

JSP / web-inf / user 디렉토리에있는 new.jsp 파일 (단지 양식 만 가능)

<form:form method="post" action="new.html">
            <fieldset>
               <table>
                  <tr>
                     <td>
                        <form:label path="firstname">FirstName</form:label>
                     </td>
                     <td>
                        <form:input path="firstname" />
                        <form:errors path="firstname" />
                     </td>
                  </tr>
                  <tr>
                     <td>
                        <form:label path="surname">Surname</form:label>
                     </td>
                     <td>
                        <form:input path="surname" />
                        <form:errors path="surname" />
                     </td>
                  </tr>
               </table>
            </fieldset>
            <div>
               <button type="submit" id="btOk">Ok</button>
            </div>
</form:form>

디스패처 servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="controllers" />
    <context:component-scan base-package="validators" />

   <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

문제는 디스플레이 검증 메시지입니다. 유효성 검사가 성공하고 변수 result (BindingResult)에 오류가 있습니다. 컨트롤러 반환 코드의 일부를 따릅니다.

if(result.hasErrors()){
         return new ModelAndView("/user/new","command",user);

또 다른 방법은 주석 유효성 검사 (사용자 정의 유효성 검사기를 preffer)를 사용하는 것입니다. 그러나 입력 필드가 비어있을 때 유효성 검사 메시지가 표시되지 않는 이유는 무엇입니까?

어떻게 할 수 있는지 예를 들어 주시겠습니까?

답변 감사합니다.

해결법

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

    1.이는 뷰와 컨트롤러의 기본 모델 특성 이름이 일치하지 않기 때문에 발생합니다.

    이는 뷰와 컨트롤러의 기본 모델 특성 이름이 일치하지 않기 때문에 발생합니다.

    즉, 뷰어가 model 속성 명령에 대한 오류를 표시하려고 시도하는 동안 유효성 검사기로 생성 된 오류 메시지는 userModel이라는 모델 속성에 바인딩됩니다.

    뷰 (

    ) 또는 컨트롤러 (@ModelAttribute ( "command"))에서 명시 적으로 모델 속성 이름을 설정해야합니다.

  2. from https://stackoverflow.com/questions/4031266/spring-3-mvc-show-validation-message-with-custom-validator by cc-by-sa and MIT license