Spring mvc HandlerMapping VS HandlerAdapter

时间:2014-04-27 15:19:10

标签: spring spring-mvc

我一直在阅读Spring MVC HandlerMappingHandlerAdapter,但我对这两个概念感到困惑。我可以理解HandlerMapping用于将传入的HTTP请求映射到控制器但是{ {1}} what is the use of HandlerAdapter?
why do we use it?
请帮助我。谢谢!!

2 个答案:

答案 0 :(得分:10)

自从在Spring 3.1中引入RequestMappingHandlerMapping和RequestMappingHandlerAdapter以来,区别更为简单: RequestMappingHandlerMapping为给定请求查找适当的处理程序方法。 RequestMappingHandlerAdapter执行此方法,为其提供所有参数。

答案 1 :(得分:-1)

HandlerMapping 用于将请求映射到处理程序,即控制器。例如:DefaultAnnotationHandlerMapping,SimpleUrlHandlerMapping,BeanNameUrlHandlerMapping。 DefaultAnnotationHandlerMapping。

<mvc:annotation-driven />声明明确支持注释驱动的MVC控制器。标记配置两个bean(映射和适配器)DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter,因此您无需在上下文配置文件中声明它们。

HandlerAdapter 基本上是一个便于在Spring MVC中以非常灵活的方式处理HTTP请求的接口。 DispatcherServlet不直接调用该方法 - 它基本上充当它自己和处理程序对象之间的桥梁,导致松散耦合的设计。

public interface HandlerAdapter {
    //check if a particular handler instance is supported or not. 
    boolean supports(Object handler);

   //used to handle a particular HTTP request and returns ModelAndView object to DispatcherServlet
    ModelAndView handle(
      HttpServletRequest request,
      HttpServletResponse response, 
      Object handler) throws Exception;

    long getLastModified(HttpServletRequest request, Object handler);
}

HandlerAdapter的类型:
enter image description here

AnnotationMethodHandlerAdapter :执行使用@RequestMapping注释的方法。 AnnotationMethodHandlerAdapter已被弃用,并由Spring 3.1+中的 RequestMappingHandlerAdapter 替换。

SimpleControllerHandlerAdapter:这是Spring MVC注册的默认处理程序适配器。它处理实现Controller接口的类,用于将请求转发给控制器对象。

如果Web应用程序仅使用控制器,那么我们不需要配置任何HandlerAdapter,因为框架使用此类作为处理请求的默认适配器。

让我们使用旧式控制器(实现Controller接口)定义一个简单的控制器类:

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>

for more

相关问题