it-source

BindingResult에서 컨트롤러 오류 텍스트를 가져오는 방법

criticalcode 2023. 3. 2. 22:20
반응형

BindingResult에서 컨트롤러 오류 텍스트를 가져오는 방법

JSON을 반환하는 컨트롤러가 있습니다.스프링 주석을 통해 검증되는 형태를 취합니다.BindingResult에서 FieldError 목록을 가져올 수 있지만 JSP가 태그에 표시하는 텍스트가 포함되어 있지 않습니다.에러 텍스트를 JSON으로 반송하려면 어떻게 해야 하나요?

@RequestMapping(method = RequestMethod.POST)
public
@ResponseBody
JSONResponse submit(@Valid AnswerForm answerForm, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {

    if (result.hasErrors()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JSONResponse r = new JSONResponse();
        r.setStatus(JSONResponseStatus.ERROR);
        //HOW DO I GET ERROR MESSAGES OUT OF BindingResult??? 
    } else {
        JSONResponse r = new JSONResponse();
        r.setStatus(JSONResponseStatus.OK);
        return r;
    }

}

JSONREsponse 클래스는 POJO일 뿐입니다.

public class JSONResponse implements Serializable {
    private JSONResponseStatus status;
    private String error;
    private Map<String,String> errors;
    private Map<String,Object> data;

...getters and setters...
}

BindingResult.getAllErrors()를 호출하면 FieldError 객체의 배열이 반환되지만 실제 오류는 없습니다.

면책사항:아직 Spring-MVC 3.0을 사용하지 않습니다.

그러나 Spring 2.5에서 사용한 것과 동일한 접근방식을 통해 고객의 요구를 충족시킬 수 있습니다.

for (Object object : bindingResult.getAllErrors()) {
    if(object instanceof FieldError) {
        FieldError fieldError = (FieldError) object;

        System.out.println(fieldError.getCode());
    }

    if(object instanceof ObjectError) {
        ObjectError objectError = (ObjectError) object;

        System.out.println(objectError.getCode());
    }
}

당신에게 도움이 되길 바랍니다.

갱신하다

리소스 번들에 의해 제공되는 메시지를 가져오려면 등록된 messageSource 인스턴스가 필요합니다(messageSource라고 불릴 필요가 있습니다).

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="ValidationMessages"/>
</bean>

뷰 내에 MessageSource 인스턴스 삽입

@Autowired
private MessageSource messageSource;

그리고 당신의 메시지를 받으려면 다음과 같이 하세요.

for (Object object : bindingResult.getAllErrors()) {
    if(object instanceof FieldError) {
        FieldError fieldError = (FieldError) object;

        /**
          * Use null as second parameter if you do not use i18n (internationalization)
          */

        String message = messageSource.getMessage(fieldError, null);
    }
}

검증자의 외관은 다음과 같습니다.

/**
  * Use null as fourth parameter if you do not want a default message
  */
errors.rejectValue("<FIELD_NAME_GOES_HERE>", "answerform.questionId.invalid", new Object [] {"123"}, null);

최근에 이 문제를 발견하고 더 쉬운 방법을 찾았습니다(Spring 3의 지원일지도 모릅니다).

    List<FieldError> errors = bindingResult.getFieldErrors();
    for (FieldError error : errors ) {
        System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
    }

메시지 소스를 변경하거나 추가할 필요가 없습니다.

Java 8 스트림 사용

bindingResult
.getFieldErrors()
.stream()
.forEach(f -> System.out.println(f.getField() + ": " + f.getDefaultMessage()));

BEAN XML:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>messages</value>
        </list>            
    </property>
</bean>

<bean id="messageAccessor" class="org.springframework.context.support.MessageSourceAccessor">
    <constructor-arg index="0" ref="messageSource"/>
</bean> 

자바:

for (FieldError error : errors.getFieldErrors()) {
    logger.debug(messageAccessor.getMessage(error));
}

메모: Errors.getDefaultMessage()를 호출해도 코드 + arg에서 생성된 것과 동일한 메시지가 반환되지 않습니다.default Message는 Errors.rejectValue() 메서드를 호출할 때 정의된 개별 값입니다.여기에서 Errors.rejectValue() API를 참조하십시오.

WebMvcConfigurerAdapter:

@Bean(name = "messageSourceAccessor")
public org.springframework.context.support.MessageSourceAccessor messageSourceAccessor() {
    return new MessageSourceAccessor( messageSource());
}

컨트롤러:

@Autowired
@Qualifier("messageSourceAccessor")
private MessageSourceAccessor           messageSourceAccessor;
...

StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
    if ( error instanceof FieldError) {
        FieldError fe = (FieldError) error;
        sb.append( fe.getField());
        sb.append( ": ");
    }
    sb.append( messageSourceAccessor.getMessage( error));
    sb.append( "<br />");
}

입수 방법Map각 필드에 관련된 모든 오류:

@Autowired
private MessageSource messageSource;

Map<String, List<String>> errorMap = bindingResult.getFieldErrors().stream()
    .collect(Collectors.groupingBy(FieldError::getField, 
    Collectors.mapping(e -> messageSource.getMessage(e, LocaleContextHolder.getLocale()), 
                        Collectors.toList())));
//In this example, each field/key is mapped to a 
//List of all the errors associated with that field

입수 방법Map각 필드에 관련된 오류가 하나로 병합됨String:

@Autowired
private MessageSource messageSource;

Map<String, String> errorMap = bindingResult.getFieldErrors().stream()
        .collect(Collectors
                .toMap(FieldError::getField, 
                    e -> messageSource.getMessage(e, LocaleContextHolder.getLocale()), 
                    (a,b)->a + "<br/>" + b));
//In this example, multiple errors for the same field are separated with <br/>, 
//the line break element, to be easily displayed on the front end

언급URL : https://stackoverflow.com/questions/2751603/how-to-get-error-text-in-controller-from-bindingresult

반응형