Spring MVC 之 HandlerMapping

HanderMapping的做用 

HandlerMapping類定義了request與handler之間映射關係。查找request對應的handler是SpringMVC DispatcherServlet處理request的第一步。經過分析request的url和消息頭headers查找對應的handler對象handlerExecutionChain ,而後DispatcherServlet會執行handlerExecutionChain 中包含的處理器方法handler method和一系列前置和後置的方法攔截器handler Interceptor。java

public interface HandlerMapping {
      HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

HandlerMapping的子類

 

  • RequestMappingHandlerMapping

RequestMappingHandlerMapping-根據@Controller註解的類中的類級別和方法級別的@RequestMapping註解來建立定義了request和handler method之間映射關係的RequestMappingInfo實例。基本用法以下:app

@Controller
public class WelcomeController 
{
    @RequestMapping("/welcome")
    protected ModelAndView someMethod() throws Exception {
        System.out.println("Inside WelcomeController");

        ModelAndView model = new ModelAndView("welcome");
        model.addObject("message", "JavaInterviewPoint");

        return model;
    }

}
  • BeanNameUrlHandlerMapping

BeanNameUrlHandlerMapping-從URL到以斜槓/開頭的bean名稱的映射的HandlerMapping接口的實現類,與Struts中URL映射到action名稱的方式相似。其特色是,每次只能註冊一個url與bean的映射關係,若是將多個url映射到一個bean上,須要屢次註冊。基本用法以下:ide

//用法1,直接在@Controller註解上定義別名,註冊映射/welcome->WelcomeController
@Controller("/welcome")
public class WelcomeController  extends AbstractController
{
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
                                                 HttpServletResponse response) throws Exception {
       
        ModelAndView model = new ModelAndView("welcome");
        model.addObject("message", "JavaInterviewPoint");

        return model;
    }
}
//用法2,在@Configuration註解類中定義指定別名的Bean,註冊映射/welcome一、/welcome2->WelcomeController
@Configuration
public class BeanNameUrlHandlerMappingConfig {
    @Bean
    BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
        return new BeanNameUrlHandlerMapping();
    }
 
    @Bean({"/welcome1","/welcome2"})
    public WelcomeController welcome() {
        return new WelcomeController();
    }
}
  • SimpleUrlHandlerMapping

SimpleUrlHandlerMapping-從URL到request處理程序bean的映射的HandlerMapping接口的實現類。支持映射到bean實例以及映射到bean名稱。url

SimpleUrlHandlerMapping與BeanNameUrlHandlerMapping相似,都是基於url和bean映射關係,可是SimpleUrlHandlerMapping更靈活。其setUrlMap方法支持一次註冊多個Url映射關係。spa

//註冊映射/welcome一、/welcome2->WelcomeController
@Configuration
public class UrlHandlerMappingConfig {
 @Bean
    SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        Map<String, Object> urlMap = new LinkedHashMap<String, Object>();
        urlMap.put("welcome1","welcomeController");
        urlMap.put("welcome2","welcomeController");
        SimpleUrlHandlerMapping handlerMapping=new SimpleUrlHandlerMapping();
        handlerMapping.setUrlMap(urlMap);
        return handlerMapping;
    }

    @Bean WelcomeController welcomeController(){
        return new WelcomeController();
    }
 
     
}
相關文章
相關標籤/搜索