HandlerMapping 详解

文章目录

  • 一、BeanNameUrlHandlerMapping
    • 1. 代码示例
    • 2. 请求路径:`/mytest`
    • 3. 不足:
  • 二、SimpleUrlHandlerMapping
    • 1. 示例代码
    • 2. 请求路径:`/test1` `/test2`

### Spring MVC 结构
-------------------------------------------------
HandlerMapping
	- AbstractHandlerMapping
		- AbstractUrlHandlerMapping		//XML解析
			- SimpleUrlHandlerMapping	
			- AbstractDetectingUrlHandlerMapping
				- BeanNameUrlHandlerMapping
		- AbstractHandlerMethodMapping	//注解解析
			- RequestMappingInfoHandlerMapping
				- RequestMappingHandlerMapping
		- EmptyHandlerMapping

一、BeanNameUrlHandlerMapping

1. 代码示例

  • TestController
	package com.zxguan.template.controller;
	import org.springframework.web.servlet.ModelAndView;
	import org.springframework.web.servlet.mvc.AbstractController;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	/**
	 * @author zxguan
	 * @create 2019-08-16 14:57
	 **/
	public class TestController extends AbstractController {
		@Override
		protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
			ModelAndView model = new ModelAndView("home");
			return model;
		}
	}
  • xml 配置
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean name="/mytest" class="com.zxguan.template.controller.TestController" />

2. 请求路径:/mytest

3. 不足:

  • bean name 属性必须要以 “/” 开头
  • 多个 url 请求对应同一个 Controller,无法处理。需要配置多个处理器。

二、SimpleUrlHandlerMapping

1. 示例代码

  • TestController
	同上
  • xml 配置
    <bean name="testController" class="com.zxguan.template.controller.TestController" />
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="urlMap">
            <map>
                <entry key="/test1" value="testController"></entry>
                <entry key="/test2" value="testController"></entry>
            </map>
        </property>
    </bean>

2. 请求路径:/test1 /test2

你可能感兴趣的:(#,Spring,MVC)