处理器映射器:根据请求URL查找对应的Handler(处理器)
处理器适配器:根据请求URL执行对应的Handler(处理器)
处理器适配器能调用并执行符合要求的handler,其中,适配器的support方法表明了符合该适配器要求的handler需要实现什么接口,下面,我介绍两种常见的非注解开发的处理器适配器
1、SimpleControllerHandlerAdapter(org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter)
源码:
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
public boolean supports(Object handler) {
return (handler instanceof Controller);
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return ((Controller) handler).handleRequest(request, response);
}
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
}
}
support方法表明:符合该适配器的handler必须实现Controller接口,该接口源码:
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* Base Controller interface, representing a component that receives
* <code>HttpServletRequest</code> and <code>HttpServletResponse</code>
* instances just like a <code>HttpServlet</code> but is able to
* participate in an MVC workflow. Controllers are comparable to the
* notion of a Struts <code>Action</code>.
*
* <p>Any implementation of the Controller interface should be a
* <i>reusable, thread-safe</i> class, capable of handling multiple
* HTTP requests throughout the lifecycle of an application. To be able to
* configure a Controller easily, Controller implementations are encouraged
* to be (and usually are) JavaBeans.
* </p>
*
* <p><b><a name="workflow">Workflow</a></b></p>
*
* <p>
* After a <cde>DispatcherServlet</code> has received a request and has
* done its work to resolve locales, themes and suchlike, it then tries
* to resolve a Controller, using a
* {@link org.springframework.web.servlet.HandlerMapping HandlerMapping}.
* When a Controller has been found to handle the request, the
* {@link #handleRequest(HttpServletRequest, HttpServletResponse) handleRequest}
* method of the located Controller will be invoked; the located Controller
* is then responsible for handling the actual request and - if applicable -
* returning an appropriate
* {@link org.springframework.web.servlet.ModelAndView ModelAndView}.
* So actually, this method is the main entrypoint for the
* {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet}
* which delegates requests to controllers.</p>
*
* <p>So basically any <i>direct</i> implementation of the Controller interface
* just handles HttpServletRequests and should return a ModelAndView, to be further
* interpreted by the DispatcherServlet. Any additional functionality such as
* optional validation, form handling, etc should be obtained through extending
* one of the abstract controller classes mentioned above.</p>
*
* <p><b>Notes on design and testing</b></p>
*
* <p>The Controller interface is explicitly designed to operate on HttpServletRequest
* and HttpServletResponse objects, just like an HttpServlet. It does not aim to
* decouple itself from the Servlet API, in contrast to, for example, WebWork, JSF or Tapestry.
* Instead, the full power of the Servlet API is available, allowing Controllers to be
* general-purpose: a Controller is able to not only handle web user interface
* requests but also to process remoting protocols or to generate reports on demand.</p>
*
* <p>Controllers can easily be tested by passing in mock objects for the
* HttpServletRequest and HttpServletResponse objects as parameters to the
* {@link #handleRequest(HttpServletRequest, HttpServletResponse) handleRequest}
* method. As a convenience, Spring ships with a set of Servlet API mocks
* that are suitable for testing any kind of web components, but are particularly
* suitable for testing Spring web controllers. In contrast to a Struts Action,
* there is no need to mock the ActionServlet or any other infrastructure;
* HttpServletRequest and HttpServletResponse are sufficient.</p>
*
* <p>If Controllers need to be aware of specific environment references, they can
* choose to implement specific awareness interfaces, just like any other bean in a
* Spring (web) application context can do, for example:</p>
* <ul>
* <li><code>org.springframework.context.ApplicationContextAware</code></li>
* <li><code>org.springframework.context.ResourceLoaderAware</code></li>
* <li><code>org.springframework.web.context.ServletContextAware</code></li>
* </ul>
*
* <p>Such environment references can easily be passed in testing environments,
* through the corresponding setters defined in the respective awareness interfaces.
* In general, it is recommended to keep the dependencies as minimal as possible:
* for example, if all you need is resource loading, implement ResourceLoaderAware only.
* Alternatively, derive from the WebApplicationObjectSupport base class, which gives
* you all those references through convenient accessors - but requires an
* ApplicationContext reference on initialization.
*
* <p>Controllers can optionally implement the {@link LastModified} interface.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see LastModified
* @see SimpleControllerHandlerAdapter
* @see AbstractController
* @see org.springframework.mock.web.MockHttpServletRequest
* @see org.springframework.mock.web.MockHttpServletResponse
* @see org.springframework.context.ApplicationContextAware
* @see org.springframework.context.ResourceLoaderAware
* @see org.springframework.web.context.ServletContextAware
* @see org.springframework.web.context.support.WebApplicationObjectSupport
*/
public interface Controller {
/**
* Process the request and return a ModelAndView object which the DispatcherServlet
* will render. A <code>null</code> return value is not an error: It indicates that
* this object completed request processing itself, thus there is no ModelAndView
* to render.
* @param request current HTTP request
* @param response current HTTP response
* @return a ModelAndView to render, or <code>null</code> if handled directly
* @throws Exception in case of errors
*/
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
下面给出一个handler的例子:
package com.js.springmvc01;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.js.po.Items;
/**
* 第一个controller
* 入门程序:商品列表的查询
* @author jiangs
*
*/
public class ItemController01 implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//使用静态数据把商品列表显示在jsp页面
List<Items> itemsList = new ArrayList<Items>();
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setDetail("ThinkPad T430联想笔记本电脑");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//将list传到页面
// 原来的做法,是set到request域中,现在使用modelandview来做
// request.setAttribute("itemsList", itemsList);
//定义modelandview对象
ModelAndView modelAndView = new ModelAndView();
//将数据填充到request域
modelAndView.addObject("itemsList", itemsList);
//指定转发的jsp页面
//指定jsp的路径
modelAndView.setViewName("/WEB-INF/jsp/itemsList.jsp");
return modelAndView;
}
}
其中,ModelAndView对象是springmvc封装的模型视图对象。
2、HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter)
源码:
public class HttpRequestHandlerAdapter implements HandlerAdapter {
public boolean supports(Object handler) {
return (handler instanceof HttpRequestHandler);
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
((HttpRequestHandler) handler).handleRequest(request, response);
return null;
}
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
}
}
通过support方法可知,符合该适配器要求的handler必须实现HttpRequestHandler接口,该接口源码:
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Plain handler interface for components that process HTTP requests,
* analogous to a Servlet. Only declares {@link javax.servlet.ServletException}
* and {@link java.io.IOException}, to allow for usage within any
* {@link javax.servlet.http.HttpServlet}}. This interface is essentially the
* direct equivalent of an HttpServlet, reduced to a central handle method.
*
* <p>The easiest way to expose an HttpRequestHandler bean in Spring style
* is to define it in Spring's root web application context and define
* an {@link org.springframework.web.context.support.HttpRequestHandlerServlet}
* in <code>web.xml</code>, pointing at the target HttpRequestHandler bean
* through its <code>servlet-name</code> which needs to match the target bean name.
*
* <p>Supported as a handler type within Spring's
* {@link org.springframework.web.servlet.DispatcherServlet}, being able
* to interact with the dispatcher's advanced mapping and interception
* facilities. This is the recommended way of exposing an HttpRequestHandler,
* while keeping the handler implementations free of direct dependencies
* on a DispatcherServlet environment.
*
* <p>Typically implemented to generate binary responses directly,
* with no separate view resource involved. This differentiates it from a
* {@link org.springframework.web.servlet.mvc.Controller} within Spring's Web MVC
* framework. The lack of a {@link org.springframework.web.servlet.ModelAndView}
* return value gives a clearer signature to callers other than the
* DispatcherServlet, indicating that there will never be a view to render.
*
* <p>As of Spring 2.0, Spring's HTTP-based remote exporters, such as
* {@link org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter}
* and {@link org.springframework.remoting.caucho.HessianServiceExporter},
* implement this interface rather than the more extensive Controller interface,
* for minimal dependencies on Spring-specific web infrastructure.
*
* <p>Note that HttpRequestHandlers may optionally implement the
* {@link org.springframework.web.servlet.mvc.LastModified} interface,
* just like Controllers can, <i>provided that they run within Spring's
* DispatcherServlet</i>. However, this is usually not necessary, since
* HttpRequestHandlers typically only support POST requests to begin with.
* Alternatively, a handler may implement the "If-Modified-Since" HTTP
* header processing manually within its <code>handle</code> method.
*
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.context.support.HttpRequestHandlerServlet
* @see org.springframework.web.servlet.DispatcherServlet
* @see org.springframework.web.servlet.ModelAndView
* @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.LastModified
* @see org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
* @see org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter
* @see org.springframework.remoting.caucho.HessianServiceExporter
* @see org.springframework.remoting.caucho.BurlapServiceExporter
*/
public interface HttpRequestHandler {
/**
* Process the given request, generating a response.
* @param request current HTTP request
* @param response current HTTP response
* @throws ServletException in case of general errors
* @throws IOException in case of I/O errors
*/
void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
}
下面就是一个handler的例子:
package com.js.springmvc01;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.js.po.Items;
/**
* 第2个controller
* 适配:HttpRequestHandlerAdapter,
* 该适配器要求实现HttpRequestHandler接口
* 入门程序:商品列表的查询
* @author jiangs
*
*/
public class ItemController02 implements HttpRequestHandler{
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//使用静态数据把商品列表显示在jsp页面
List<Items> itemsList = new ArrayList<Items>();
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setDetail("ThinkPad T430联想笔记本电脑");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
request.setAttribute("itemsList", itemsList);
//转发到jsp页面
request.getRequestDispatcher("/WEB-INF/jsp/itemsList.jsp").forward(request, response);
}
}
比较可知,HttpRequestHandler接口中没有ModelAndView对象,所以我们使用requet对象来进行请求转发。