본문 바로가기

Web/spring

[Spring] HandlerAdapters in Spring MVC

728x90

https://www.baeldung.com/spring-mvc-handler-adapters

 


 

 

on the various handler adapters implementations available in the Spring framework.

 

HandlerAdapter는 Spring MVC에 유연한 방식으로 HTTP 요청 처리를 용이하게 할 수 있는 interface이다

메소드를 특정 URL에 매핑하는 HandlerMapping과 함께 사용한다

 

DispatcherServlet은 HandlerAdapter를 사용하여 이 메소드를 호출한다.

Servlet이 메소드를 직접 호출하는게 아니다. 기본적으로 자신과 핸들러 객체 사이의 bridge 역할로 느슨한 결합(loosely coupling) 설계이다.

 

 

public interface HandlerAdapter {
    boolean supports(Object handler);
    
    ModelAndView handle(
      HttpServletRequest request,
      HttpServletResponse response, 
      Object handler) throws Exception;
    
    long getLastModified(HttpServletRequest request, Object handler);
}

supports API는 특정 핸들러 인스턴스가 지원되는지 여부를 확인할 때 사용된다.

이 메소드는 핸들러 인스턴스의 지원 여부를 확인하기 위해 이 인터페으스의 handle()메소드를 호출 하기전에 먼저 호출해야한다

 

핸들 API  특정 HTTP 요청을 처리하는 데 사용된다.

이 메서드는 HttpServletRequest  HttpServletResponse 개체를 매개 변수로 전달하여 핸들러를 호출한다.

핸들러는 애플리케이션 로직을 실행하고 ModelAndView 객체를 반환하며 DispatcherServlet 에 의해 처리된다

 

 

 

2023.3.23 기준 최신 버전

implementation 'org.springframework:spring-webmvc:6.0.7'

 

 


 

 

Types of HandlerAdapter

 

SimpleControllerHandlerAdapter

Spring MVC에 등록된 기본 핸들러 어댑터로

Controller interface 구현하는 클래스를 다루고, 컨트롤러 개체에 요청을 전달한다

기본 컨트롤러만 사용할 경우 기본 어댑터가 있기에 구현할 필요가 없다

 

이전 스타일의 컨트롤러에 컨트롤러 인터페이스를 구현한 방식의 정의이다

public class SimpleController implements Controller {
    @Override
    public ModelAndView handleRequest(
      HttpServletRequest request, 
      HttpServletResponse response) throws Exception {
        
        ModelAndView model = new ModelAndView("Greeting");
        model.addObject("message", "Dinesh Madhwal");
        return model;
    }
}

 

XML 구성

<beans ...>
    <bean name="/greeting.html"
      class="com.baeldung.spring.controller.SimpleControllerHandlerAdapterExample"/>
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>복사

BeanNameUrlHandlerMapping 클래스  이 핸들러 어댑터의 매핑 클래스이다.

 

BeanFactory 에 사용자 정의 핸들러 어댑터가 정의된 경우 이 어댑터는 자동으로 등록되는게 아니다. 

따라서 컨텍스트에서 명시적으로 정의해야 한다. 

정의되지 않고 사용자 정의 핸들러 어댑터를 정의한 경우 핸들러에 대한 어댑터가 지정되지 않았다는 예외가 발생한다.

 

 

 

SimpleServletHandlerAdapter

handlerAdapter를 사용하면 모든 Servlet을 이용하여 요청을 처리 하기 위해 DispatcherServlet과 함께 작업할 수 있다

service() 메소드를 호출하여 DispatcherServlet의 요청을 적절한 서비스에 전달한다

 

서블릿 인터페이스를 구현하는 빈은 이 어댑터에 의해 자동으로 처리된다.

기본적으로 등록되지 않으며 DispatcherServlet 의 구성 파일에서 다른 일반 빈처럼 등록해야 한다.

<bean name="simpleServletHandlerAdapter" 
  class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter" />

 

 

 

AnnotationMethodHandlerAdapter

이 어댑터 클래스는 @RequestMapping 애노테이션이 달린 메소드를 실행할 때 사용한다

HTTP 메서드 및 HTTP 경로를 기반으로 메서드를 매핑하는 데 사용한다.

DefaultAnnotationHandlerMapping이며 유형 수준에서 @RequestMapping 주석을 처리하는 데 사용되고 AnnotationMethodHandlerAdaptor는 메서드 수준에서 처리하는 데 사용된다

 

두 클래스는 DispatcherServlet이 초기화될 때 프레임워크에 이미 등록되어있다.

다른 handler adapters가 정의되어있으면 구성파일에서 정의해야한다.

 

Controller Class에 정의

@Controller
public class AnnotationHandler {
    @RequestMapping("/annotedName")
    public ModelAndView getEmployeeName() {
        ModelAndView model = new ModelAndView("Greeting");        
        model.addObject("message", "Dinesh");       
        return model;  
    }  
}

@Controller 주석은 이 클래스가 컨트롤러 역할을 수행함을 나타낸다.

@RequestMapping 주석은 getEmployeeName() 메서드  URL /name에 매핑한다.

 

 

 

Java 구성을 사용하는 방법

@ComponentScan("com.baeldung.spring.controller")
@Configuration
@EnableWebMvc
public class ApplicationConfiguration implements WebMvcConfigurer {
    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

 

XML 구성을 사용하는 방법

 

spring-servlet_AnnotationMethodHandlerAdapter.xml 파일에 정의된 첫 번째 접근 방식

<beans ...>
    <context:component-scan base-package="com.baeldung.spring.controller" />
    <bean 
      class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    <bean 
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

 

 

RequestMappingHandlerAdapter

 Spring 3.2에서 AnnotationMethodHandlerAdaptor 핸들러 어댑터를 더 이상 사용하지 않는다

@RequestMapping 주석 이 달린 메서드를 실행하는 RequestMappingHandlerMapping 클래스 와 함께 사용된다

 

 

RequestMappingHandlerMapping은 핸들러 에 대한 요청 URI의 매핑을 유지하는 데 사용된다

핸들러가 확보되면 DispatcherServlet은 요청 을 적절한 핸들러 어댑터로 디스패치한 다음 handlerMethod ()를 호출한다.

 

안쓰는 코드 및 XML 예제 코드는 생략함

 

Java 구성을 사용하는 방법

@ComponentScan("com.baeldung.spring.controller")
@Configuration
@EnableWebMvc
public class ServletConfig implements WebMvcConfigurer {
    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

 

 

 

 

HttpRequestHandlerAdapter

이 핸들러 어댑터는 HttpRequest 를 처리하는 핸들러에 사용된다.

요청을 처리하고 응답을 생성하기 위한 단일 handleRequest() 메서드를 포함하는 HttpRequestHandler 인터페이스를 구현한다.

 

이 메서드의 반환 유형은 무효이며 다른 핸들러 어댑터에서 생성된 ModelAndView 반환 유형을 생성하지 않는다

기본적으로 이진 응답을 생성하는 데 사용되며 렌더링할 뷰를 생성하지 않는다.

 

 

 

Running the Application 

If the application is deployed on localhost with the port number 8082 and the context-root is spring-mvc-handlers:

http://localhost:8082/spring-mvc-handlers/
728x90