Spring MVC 使用SimpleUrlHandlerMapping做映射处理的简单用例

xml中做如下配置

<bean id="simpleControllerTest" class="com.jake.SimpleControllerTest"/>

<bean
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <value>
        /homepage=simpleControllerTest
        <!--可以在这里添加更多的映射-->
        <!--格式/xxx=xxx 有无加斜杠无没有影响-->
        </value>
    </property>
</bean>

SimpleControllerTest类

继承自org.springframework.web.servlet.mvc.Controller,注意和org.springframework.stereotype.Controller注解类区分开

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class SimpleControllerTest implements Controller{

    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //do your things here...
        return new ModelAndView("homepage");
    }

}

访问

访问localhost:8080/app/homepage
就可以看到跳转到homepage页面

问题:为什么SimpleControllerTest要继承Controller

因为SimpleUrlHandlerMapping对应的处理器是HandlerAdapter的子实现类SimpleControllerHandlerAdapter

DispatcherServlet中的doDispatcher调用getHandlerAdapter方法返回找可用的处理器

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ...
        // Determine handler for the current request.
        mappedHandler = getHandler(processedRequest, false);
        // Determine handler adapter for the current request.
        HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
        ... 
}

遍历Spring中可用的处理器

protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
    for (HandlerAdapter ha : this.handlerAdapters) {
        if (logger.isTraceEnabled()) {
            logger.trace("Testing handler adapter [" + ha + "]");
        }
        if (ha.supports(handler)) {
            return ha;
        }
    }
    throw new ServletException("No adapter for handler [" + handler +
            "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}

ha.supports(handler)中的handler是我们的类实例simpleControllerTest(至于为什么不是讨论范畴,读者可以研究下DispatcherServlet的getHandler方法)。在众多Adapter中,只有SimpleControllerHandlerAdapter需要我们的类去实现Controller接口。所以SimpleControllerTest要继承Controller,ha.supports(handler)才为真,返回SimpleControllerHandlerAdapter,然后去处理SimpleControllerTest的方法handleRequest。

public class SimpleControllerHandlerAdapter implements HandlerAdapter {

    public boolean supports(Object handler) {
        return (handler instanceof Controller);
    }

    ...
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值