Spingmvc中的HandlerMapping负责解析请求URL,对应到Handler进行处理(这里的Handler一般为Controller里的一个方法method,也可以为servlet或者Controller等)。

HandlerMapping有三种比较常见

 

  1. BeanNameUrlHandlerMapping 根据bean标签的名称找到对应的Controller

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    
    <bean name="/my.do" class="com.zhiyou100.hhz.controller.MyController2"></bean>    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

 

 

  

  2. SimpleUrlHandlerMapping 根据beanid查找对应的Controller类。

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/a.do">my1</prop>
                <prop key="/b.do">my2</prop>
            </props>
        </property>
    
        <bean id="/my1" class="com.zhiyou100.hhz.controller.MyController1"></bean>
    <bean  id="/my2" class="com.zhiyou100.hhz.controller.MyController2"></bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

 

  3. ControllerClassNameHandlerMapping 根据controller类的名字找到对应的Controller

  注意除了后缀用Controller时首字C为大写,其他都为小写

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean> 
    <bean class="com.zhiyou100.hhz.controller.MyController1"></bean>
    <bean class="com.zhiyou100.hhz.controller.MyController2"></bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>