본문 바로가기

Web/spring

[Spring framework Web MVC docs] 1.3.5 DataBinder ~ 1.3.6 Exception

728x90

공부할때마다 느끼지만.....

영어를.....잘했다면.... 번역기 안돌리고...

이게 맞게 해석한건가... 걱정하면서...공부를...안할텐데..........

......또르르...... 아무튼...

오늘 목표는 1.3.7 까지

 

 

 

 

틀린 해석이 있다면 알려주세요

 


 

 

 

1.3.5 DataBinder

 

@Controller or @ControllerAdvice 는 WebDataBinder 의 인스턴스를 초기화하는 @InitBinder 를 사용할 수 있다.

 

  • Bind request parameters (that is, form or query data) to a model object.
  • Convert String-based request values (such as request parameters, path variables, headers, cookies, and others) to the target type of controller method arguments.
  • Format model object values as String values when rendering HTML forms.

 

@InitBinder 는 컨트롤별 PropertyEditor 또는 Converter, Fomatter 구성 요소를 등록할 수 있고

Converter, Formatter 을 전역적으로 공유할 수 잇는 FormattingConversionService 를 사용할 수 있다

 

 

@Controller
public class FormController {

    @InitBinder 
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    // ...
}

 

custom formatter

@Controller
public class FormController {

    @InitBinder 
    protected void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }

    // ...
}

 

 

 

 

 

Model Design

 

data binding 에는 HTTP 요청 매개변수를 모델 개체 및 해당 중첩 개체의 속성에 바인딩할 수 있다

 

https://www.oracle.com/java/technologies/javase/javabeans-spec.html

 

JavaBeans Spec

 

www.oracle.com

 

 

 

 

The recommended approach is to use a dedicated model object that exposes only properties that are relevant for the form submission. For example, on a form for changing a user’s email address, the model object should declare a minimum set of properties such as in the following ChangeEmailForm.

 

TTP form data endpoint 에서 속성이 노출 되는 경우가 있다

그래서 minimum set of properties 를 선언해서 주고 받는다.

 

 

public class ChangeEmailForm {

    private String oldEmailAddress;
    private String newEmailAddress;

    public void setOldEmailAddress(String oldEmailAddress) {
        this.oldEmailAddress = oldEmailAddress;
    }

    public String getOldEmailAddress() {
        return this.oldEmailAddress;
    }

    public void setNewEmailAddress(String newEmailAddress) {
        this.newEmailAddress = newEmailAddress;
    }

    public String getNewEmailAddress() {
        return this.newEmailAddress;
    }

}

 

이런 식으로 최소한의 주고받을 객체를 만들어주고

이 객체를 통해서 데이터를 바인딩 받아야만

이름 입력할 때 거기다가 간단한 쿼리문을 넣는 것으로 클라이언트가 나쁜 접근을 하는 경우를 없앤다

 

 

If you cannot or do not want to use a dedicated model object for each data binding use case, you must limit the properties that are allowed for data binding. Ideally, you can achieve this by registering allowed field patterns via the setAllowedFields() method on WebDataBinder.

 

만약 필드 패턴을 등록하려면 위의 메소드를 사용한다

 

@Controller
public class ChangeEmailController {

    @InitBinder
    void initBinder(WebDataBinder binder) {
        binder.setAllowedFields("oldEmailAddress", "newEmailAddress");
    }

    // @RequestMapping methods, etc.

}

 

허용 안하려면
setDisallowedField() 를 사용한다 하지만 

Consequently, setAllowedFields() should be favored over setDisallowedFields().

 

데이터 바인딩 목적으로 도메인 모델을 직접 노출할 때 허용 및 허용되지 않는 필드 패턴을 적절하게 구성하는 것이 매우 중요합니다. 그렇지 않으면 큰 보안 위험입니다.

 

또한 데이터 바인딩 시나리오에서 JPA 또는 Hibernate 엔터티와 같은 도메인 모델의 유형을 모델 개체로 사용 하지 않는 것이 좋습니다 .

 

 

 

 

 

 

 

 

1.3.6 Exception

 

@Controller 및 @ControllerAdvice 는

예제와 같이 @ExceptionHandler 예외처리 메서드를 가질 수 있음

 

@Controller
public class SimpleController {

    // ...

    @ExceptionHandler
    public ResponseEntity<String> handle(IOException ex) {
        // ...
    }
}

 

The exception may match against a top-level exception being propagated (e.g. a direct IOException being thrown) or against a nested cause within a wrapper exception (e.g. an IOException wrapped inside an IllegalStateException). As of 5.3, this can match at arbitrary cause levels, whereas previously only an immediate cause was considered.

For matching exception types, preferably declare the target exception as a method argument, as the preceding example shows. When multiple exception methods match, a root exception match is generally preferred to a cause exception match. More specifically, the ExceptionDepthComparator is used to sort exceptions based on their depth from the thrown exception type.

Alternatively, the annotation declaration may narrow the exception types to match, as the following example shows:

 

특정 예외 목록을 지정 해줄 수 있음

@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(IOException ex) {
    // ...
}

 

일반적인 예외처리 목록에서도 함께 사용 가능

@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(Exception ex) {
    // ...
}

 

일반적으로 루트 및 원인 예외 유형 간의 불일치 가능성을 줄이기 위해 인수 서명에서 가능한 한 구체적일 것을 권장합니다. 다중 일치 메서드를 각각 @ExceptionHandler 서명을 통해 단일 특정 예외 유형과 일치하는 개별 메서드로 나누는 것을 고려하십시오.

 

다중 @ControllerAdvice 배열에서 해당 순서로 우선 순위가 지정된 @ControllerAdvice에 기본 루트 예외 매핑을 선언하는 것이 좋습니다. 루트 예외 일치가 원인보다 선호되지만 이는 지정된 컨트롤러 또는 @ControllerAdvice 클래스의 메서드 간에 정의됩니다. 즉, 우선순위가 높은 @ControllerAdvice 빈의 원인 일치가 우선순위가 낮은 @ControllerAdvice 빈의 모든 일치(예: 루트)보다 선호됩니다.

마지막으로 @ExceptionHandler 메소드 구현은 주어진 예외 인스턴스를 원래 형식으로 다시 던짐으로써 처리를 취소하도록 선택할 수 있습니다. 이는 루트 수준 일치 또는 정적으로 확인할 수 없는 특정 컨텍스트 내의 일치에만 관심이 있는 시나리오에서 유용합니다. 다시 발생한 예외는 주어진 @ExceptionHandler 메서드가 처음부터 일치하지 않는 것처럼 나머지 해결 체인을 통해 전파됩니다.

Spring MVC에서 @ExceptionHandler 메소드에 대한 지원은 DispatcherServlet 레벨, HandlerExceptionResolver 메커니즘에 구축됩니다. 

 

 

 

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-exceptionhandlers

 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonl

docs.spring.io

 

 

 

 

Method Arguments

메서드 인수설명

예외 유형 발생한 예외에 액세스합니다.
HandlerMethod 예외를 발생시킨 컨트롤러 메서드에 액세스합니다.
WebRequest,NativeWebRequest Servlet API를 직접 사용하지 않고 요청 매개변수와 요청 및 세션 속성에 대한 일반 액세스.
jakarta.servlet.ServletRequest,jakarta.servlet.ServletResponse 특정 요청 또는 응답 유형(예: ServletRequest또는 HttpServletRequest또는 Spring의 MultipartRequest또는 MultipartHttpServletRequest)을 선택합니다.
jakarta.servlet.http.HttpSession 세션의 존재를 강제합니다. 결과적으로 그러한 주장은 결코 null.
세션 액세스는 스레드로부터 안전하지 않습니다. 여러 요청이 세션에 동시에 액세스할 수 있는 경우 RequestMappingHandlerAdapter인스턴스의 synchronizeOnSession플래그를 로 설정하는 것이 좋습니다.true
java.security.Principal 현재 인증된 사용자 — 알려진 경우 특정 Principal구현 클래스일 수 있습니다.
HttpMethod 요청의 HTTP 메서드입니다.
java.util.Locale 현재 요청 로케일은 사용 가능한 가장 구체적인 로케일로 결정됩니다 . LocaleResolver사실상 구성된 LocaleResolver또는 LocaleContextResolver.
java.util.TimeZone,java.time.ZoneId 에 의해 결정된 현재 요청과 관련된 시간대 LocaleContextResolver입니다.
java.io.OutputStream,java.io.Writer Servlet API에 의해 노출된 원시 응답 본문에 액세스합니다.
java.util.Map, org.springframework.ui.Model,org.springframework.ui.ModelMap 오류 응답을 위해 모델에 액세스합니다. 항상 비어 있습니다.
RedirectAttributes 리디렉션 시 사용할 속성(즉, 쿼리 문자열에 추가됨)과 리디렉션 후 요청이 있을 때까지 일시적으로 저장할 플래시 속성을 지정합니다. 리디렉션 속성  Flash 속성 을 참조하십시오 .
@SessionAttribute @SessionAttributes클래스 수준 선언 의 결과로 세션에 저장된 모델 속성과 달리 모든 세션 속성에 액세스합니다 . 자세한 내용 @SessionAttribute은 참조하십시오.
@RequestAttribute 요청 속성에 액세스합니다. 자세한 내용 @RequestAttribute은 참조하십시오.
 
 
 
 
 
 

 

Retrun Values

@ResponseBody 반환 값은 HttpMessageConverter인스턴스를 통해 변환되어 응답에 기록됩니다. 참조하십시오 @ResponseBody.
HttpEntity<B>,ResponseEntity<B> 반환 값은 전체 응답(HTTP 헤더 및 본문 포함)이 HttpMessageConverter인스턴스를 통해 변환되고 응답에 기록되도록 지정합니다. ResponseEntity 를 참조하십시오 .
ErrorResponse 본문에 세부 정보가 포함된 RFC 7807 오류 응답을 렌더링하려면 오류 응답을 참조하세요 .
ProblemDetail 본문에 세부 정보가 포함된 RFC 7807 오류 응답을 렌더링하려면 오류 응답을 참조하세요 .
String 구현 으로 확인되고 암시적 모델과 함께 사용되는 보기 이름 ViewResolver— 명령 개체 및 @ModelAttribute메서드를 통해 결정됩니다. 처리기 메서드는 Model 인수를 선언하여 프로그래밍 방식으로 모델을 보강할 수도 있습니다(앞에서 설명함).
View View암시적 모델과 함께 렌더링에 사용할 인스턴스 — 명령 개체 및 메서드를 통해 결정 됩니다 @ModelAttribute. 처리기 메서드는 Model인수를 선언하여 프로그래밍 방식으로 모델을 풍부하게 할 수도 있습니다(앞에서 설명함).
java.util.Map,org.springframework.ui.Model 를 통해 암시적으로 결정된 뷰 이름으로 암시적 모델에 추가할 특성 RequestToViewNameTranslator입니다.
@ModelAttribute 를 통해 암시적으로 결정된 보기 이름으로 모델에 추가할 속성 RequestToViewNameTranslator입니다.
선택 사항 @ModelAttribute입니다. 이 표 끝에 있는 "기타 반환 값"을 참조하십시오.
ModelAndView물체 사용할 보기 및 모델 속성과 선택적으로 응답 상태.
void void반환 유형(또는 반환 값)이 있는 메서드  인수 또는 주석 null도 있는 경우 응답을 완전히 처리한 것으로 간주됩니다 . 컨트롤러가 긍정 또는 타임스탬프 확인 을 수행한 경우에도 마찬가지입니다 (자세한 내용은 컨트롤러 참조).ServletResponseOutputStream@ResponseStatusETaglastModified
위의 어느 것도 사실이 아닌 경우 void반환 유형은 REST 컨트롤러에 대한 "응답 본문 없음" 또는 HTML 컨트롤러에 대한 기본 보기 이름 선택을 나타낼 수도 있습니다.
기타 반환 값 반환 값이 위의 어떤 것과도 일치하지 않고 단순 유형( BeanUtils#isSimpleProperty 에 의해 결정됨)이 아닌 경우 기본적으로 모델에 추가할 모델 속성으로 처리됩니다. 단순 유형인 경우 해결되지 않은 상태로 유지됩니다.

 

 

728x90