本文将讨论HandlerMapping,HandlerAdapter,ViewResolver组件类的具体实现。
URLHandlerMapping,利用request中包含的url信息,找到对应Handler对象,URLHandlerMapping是最典型的映射方式。
- package com.google.mvc.web.servlet.handler;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.atomic.AtomicBoolean;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.log4j.Logger;
- import com.google.mvc.web.context.WebApplicationContext;
- import com.google.mvc.web.context.WebApplicationContextAware;
- import com.google.mvc.web.servlet.HandlerMapping;
- import com.google.mvc.web.servlet.mvc.Controller;
- import com.google.mvc.web.servlet.mvc.HttpRequestHandler;
- public class URLHandlerMapping implements HandlerMapping, WebApplicationContextAware{
- private static final Logger LOGGER = Logger.getLogger(URLHandlerMapping.class);
- private WebApplicationContext wac;
- private Map<String, Object> handlerMap = new ConcurrentHashMap<String, Object>();
- private AtomicBoolean initialize = new AtomicBoolean(false);
- @Override
- public void setWebApplicationContext(WebApplicationContext wac) {
- this.wac = wac;
- }
- @Override
- public Object getHandler(HttpServletRequest request) throws Exception {
- if(LOGGER.isDebugEnabled()){
- LOGGER.debug("Find handler for request " + request.getServletPath());
- }
- if(initialize.compareAndSet(false, true)){
- Map<String, HttpRequestHandler> map1 = wac.beansOfType(HttpRequestHandler.class);
- for(String key : map1.keySet()){
- handlerMap.put(key, map1.get(key));
- }
- Map<String, Controller> map2 = wac.beansOfType(Controller.class);
- for(String key : map2.keySet()){
- handlerMap.put(key, map2.get(key));
- }
- }
- Object handler = handlerMap.get(getHandlerName(request));
- if(handler == null){
- handler = handlerMap.get("404");
- }
- return handler;
- }
- protected String getHandlerName(HttpServletRequest request){
- String path = request.getServletPath();
- int index = path.lastIndexOf('/');
- String handleName = path.substring(index + 1, path.length());
- return handleName;
- }
- }
HandlerAdapter用于把不同的Handler对象处理的结果封装成一个统一的对象ModelAndView,以达到逻辑上的一致处理。在这里,我们定义两种Handler类型
- Controller:用于处理用户的业务逻辑,并返回具体ModelAndView对象,具体接口定义如下
- package com.google.mvc.web.servlet.mvc;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.google.mvc.web.servlet.ModelAndView;
- public interface Controller {
- ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
- }
- HttpRequestHandler:用于处理简单的HTTP请求。接口定义如下
- package com.google.mvc.web.servlet.mvc;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public interface HttpRequestHandler {
- void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
- }
- package com.google.mvc.web.servlet.mvc;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class HandlerFor404 implements HttpRequestHandler {
- @Override
- public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
- response.sendRedirect("404.html");
- }
- }
我们需要为每一种不同的Handler类型指定一种HandlerAdapter,但这不是必须的。
ControllerHandlerAdapter
- package com.google.mvc.web.servlet.mvc;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.google.mvc.web.servlet.HandlerAdapter;
- import com.google.mvc.web.servlet.ModelAndView;
- public class ControllerHandlerAdapter 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) {
- return -1L;
- }
- }
HttpRequestHandlerAdapter
- package com.google.mvc.web.servlet.mvc;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.google.mvc.web.servlet.HandlerAdapter;
- import com.google.mvc.web.servlet.ModelAndView;
- public class HttpRequestHandlerAdapter implements HandlerAdapter {
- @Override
- public long getLastModified(HttpServletRequest request, Object handler) {
- return 0;
- }
- @Override
- public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- ((HttpRequestHandler) handler).handleRequest(request, response);
- return null;
- }
- @Override
- public boolean supports(Object handler) {
- return (handler instanceof HttpRequestHandler);
- }
- }
ViewResolver用于指定View的生成方式,我们先来看下AbstractView的定义
- package com.google.mvc.web.servlet.mvc;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import javax.servlet.ServletRequest;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.log4j.Logger;
- import com.google.mvc.web.servlet.View;
- public abstract class AbstractView implements View {
- private static final Logger LOGGER = Logger.getLogger(AbstractView.class);
- public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
- public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
- public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";
- public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";
- public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";
- public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";
- public static final String DEFAULT_CONTENT_TYPE = "text/html;charset=ISO-8859-1";
- private String contentType = DEFAULT_CONTENT_TYPE;
- private boolean alwaysInclude = false;
- @Override
- public String getContentType() {
- return contentType;
- }
- protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request){
- Iterator<Entry<String, Object>> it = model.entrySet().iterator();
- while (it.hasNext()) {
- Entry<String, Object> entry = it.next();
- String modelName = entry.getKey();
- Object modelValue = entry.getValue();
- if (modelValue != null) {
- request.setAttribute(modelName, modelValue);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Added model object '" + modelName + "' of type [" + modelValue.getClass().getName() +
- "] to request in view with name '" + this + "'");
- }
- } else {
- request.removeAttribute(modelName);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Removed model object '" + modelName + "' from request in view with name '"
- + this + "'");
- }
- }
- }
- }
- protected boolean useInclude(HttpServletRequest request, HttpServletResponse response) {
- return (this.alwaysInclude || request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null || response
- .isCommitted());
- }
- protected void exposeForwardRequestAttributes(HttpServletRequest request) {
- exposeRequestAttributeIfNotPresent(request, FORWARD_REQUEST_URI_ATTRIBUTE, request.getRequestURI());
- exposeRequestAttributeIfNotPresent(request, FORWARD_CONTEXT_PATH_ATTRIBUTE, request.getContextPath());
- exposeRequestAttributeIfNotPresent(request, FORWARD_SERVLET_PATH_ATTRIBUTE, request.getServletPath());
- exposeRequestAttributeIfNotPresent(request, FORWARD_PATH_INFO_ATTRIBUTE, request.getPathInfo());
- exposeRequestAttributeIfNotPresent(request, FORWARD_QUERY_STRING_ATTRIBUTE, request.getQueryString());
- }
- private void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value) {
- if (request.getAttribute(name) == null) {
- request.setAttribute(name, value);
- }
- }
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
- public boolean isAlwaysInclude() {
- return alwaysInclude;
- }
- public void setAlwaysInclude(boolean alwaysInclude) {
- this.alwaysInclude = alwaysInclude;
- }
- }
在这里我们仅实现一种View类型,也就是对jsp页面的简单处理。
- package com.google.mvc.web.servlet.mvc;
- import java.io.IOException;
- import java.util.Map;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.log4j.Logger;
- public class InternalResourceView extends AbstractView {
- private static final Logger LOGGER = Logger.getLogger(InternalResourceView.class);
- private String url;
- @Override
- public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Rendering view with name '" + this + "' with model " + model);
- }
- if(model != null){
- exposeModelAsRequestAttributes(model, request);
- }
- RequestDispatcher rd = request.getRequestDispatcher(url);
- if (rd == null) {
- throw new ServletException("Could not get RequestDispatcher for ["
- + getUrl() + "]: check that this file exists within your WAR");
- }
- if (useInclude(request, response)) {
- response.setContentType(getContentType());
- rd.include(request, response);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Included resource [" + getUrl() + "] in InternalResourceView '" + url + "'");
- }
- }else {
- exposeForwardRequestAttributes(request);
- rd.forward(request, response);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Forwarded to resource [" + getUrl() + "] in InternalResourceView '" + url + "'");
- }
- }
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public String toString(){
- return this.url;
- }
- }
好了,到这里,我们再来看看ViewResolver类的实现
- package com.google.mvc.web.servlet.mvc;
- import org.apache.log4j.Logger;
- import com.google.mvc.web.servlet.View;
- import com.google.mvc.web.servlet.ViewResolver;
- public class DefaultViewResolver implements ViewResolver
- {
- private static final Logger LOGGER = Logger.getLogger(DefaultViewResolver.class);
- private String prefix = "";
- private String suffix = "";
- private Class<View> viewClass;
- @Override
- public View resolveViewName(String viewName) throws Exception {
- View view = viewClass.newInstance();
- if(view instanceof InternalResourceView){
- ((InternalResourceView)view).setUrl(prefix + viewName + suffix);
- }
- return view;
- }
- public void setViewClass(String viewClass){
- try {
- this.viewClass = (Class<View>) this.getClass().getClassLoader().loadClass(viewClass);
- } catch (ClassNotFoundException e) {
- LOGGER.error("Can't load view class " + viewClass, e);
- }
- }
- public String getPrefix() {
- return prefix;
- }
- public void setPrefix(String prefix) {
- this.prefix = prefix;
- }
- public String getSuffix() {
- return suffix;
- }
- public void setSuffix(String suffix) {
- this.suffix = suffix;
- }
- }
到这里,我们在整个MVC架构的源码实现已经完成了,下一篇,我们将介绍一个基于我们这个MVC架构的Demo。
文章来源:http://blog.csdn.net/zhiqiangzhan/article/details/4768172
相关推荐
1. **架构设计**:了解整体架构,如MVC组件间的交互方式,以及系统是如何组织和划分职责的。 2. **路由机制**:研究如何通过URL映射到相应的控制器和方法,理解请求的处理流程。 3. **模板引擎**:查看视图层是...
通过对比这两个版本的源码,开发者可以深入了解Struts 2框架的设计理念,学习如何实现Action、Interceptor、Result等核心组件,以及如何利用OGNL进行数据绑定。同时,分析版本间的差异有助于理解框架的发展趋势和...
1. **源代码文件夹**:包括了系统的所有Java源代码,这些代码可能按照MVC(Model-View-Controller)架构组织,分为模型、视图和控制器三个部分,用于实现业务逻辑、数据展示和用户交互。 2. **数据库脚本**:系统...
5. **Spring的事件驱动模型**:了解Spring如何通过ApplicationEvent和ApplicationListener实现组件间的异步通信。 6. **Spring的模块化设计**:研究不同模块(如core-container、data-access、web)之间的依赖关系...
官方原版源码spring-framework-5.1.13.RELEASE.zip为我们提供了深入了解这一框架的机会,让我们能够探究其内部工作机制,提升开发技能。 1. **Spring Framework概述** Spring Framework是Java应用程序开发的一个...
特别地,Spring MVC是Spring用于构建Web应用的重要组件,它通过DispatcherServlet、HandlerMapping、ViewResolver等机制实现了请求的路由和视图的渲染。 四、模块扩展 - Spring Framework 5.0引入了Reactive编程...
1. 架构设计:了解整体架构,包括MVC(模型-视图-控制器)模式的应用,以及各模块间的交互。 2. 数据库设计:查看数据库表结构,理解如何存储和管理菜单、订单、用户信息等数据。 3. API接口:研究与第三方支付平台...
5. **Web模块**:提供了MVC(Model-View-Controller)架构,用于构建Web应用程序。 三、源码结构分析 在解压后的文件中,我们看到三个主要的子文件: - **spring-framework-5.0.13.RELEASE-dist.zip**:包含...
《深入剖析Spring Framework 5.1.14源码》 Spring Framework作为Java开发领域中的基石,其核心...通过阅读和学习源码,我们可以深入探究DI、AOP、Web MVC、数据访问等核心概念,提升我们的编程技巧和解决问题的能力。
这个项目的名称可能暗示着它是一个基于森林主题的游戏或者互动故事应用,但具体的功能和设计,我们需要通过源码来深入探究。 首先,我们要明白iOS应用的基本构建块。一个标准的iOS应用通常由多个部分组成,包括...
Vue.js 是一款流行的前端框架,Vue Router 是 Vue.js 生态中的官方路由库,它负责管理单页应用(SPA,...随着对 Vue Router 源码的深入探究,我们也将对前端架构有更深刻的认识,为未来的项目开发打下坚实的基础。
Spring MVC 提供了一个灵活的架构,支持多种视图技术,如 JSP、FreeMarker 和 Velocity。 4. **AOP(面向切面编程)**:Spring 的 AOP 模块提供了面向切面编程的实现,允许开发者定义方法拦截器和切入点,以实现如...
这份源码提供了实现一个完整的社交媒体应用的实际案例,让我们有机会探究其背后的架构设计、功能实现以及优化策略。下面,我们将对这个项目进行详细的分析。 1. **整体架构** - **MVC/MVVM模式**:源码可能采用了...
- **MVC(Model-View-Controller)**:Spring MVC是Web开发的重要部分,源码中涉及DispatcherServlet、HandlerMapping、ViewResolver等组件,理解它们的工作原理对于Web应用的开发至关重要。 - **事务管理**:...
这个压缩包"spring-framework-2.5.4源码.rar"包含了Spring框架的核心组件和相关源代码,特别是"src"目录下的文件,这将使我们有机会探究Spring如何处理IoC(Inversion of Control)、AOP(Aspect Oriented ...
AngularJS通过MVC(模型-视图-控制器)架构模式,实现了数据绑定和依赖注入,极大地提高了Web应用的开发效率。在dist-flatboard-v1.2中,AngularJS被用来管理应用的状态,实现动态数据渲染和交互功能。通过双向数据...
学习Backbone.js,开发者需要理解MVC架构的原理,掌握事件驱动编程和数据绑定的概念。同时,对JavaScript原型链、闭包以及异步操作的理解也是必不可少的。通过阅读源码和API文档,开发者可以学习到如何有效地组织...
5. **注解驱动编程**:探究@Component、@Service、@Repository和@Controller等注解的解析过程,以及Autowired和Qualifier的工作原理。 6. **事务管理**:研究PlatformTransactionManager接口和相关的事务策略,理解...
3. **MVC(Model-View-Controller)架构**: 常见于Web应用开发,用于分离业务逻辑、数据模型和用户界面。在这个系统中,Model处理数据,View展示信息,Controller协调Model和View的交互。 4. **Servlet**: 虽然未...
同时,结合JDK库的使用,可以深入探究Spring如何利用Java的特性来实现其强大的功能。 总的来说,这个压缩包为学习Spring源码提供了一套完整的资源。从IoC到AOP,从数据访问到Web开发,通过调试代码和实例,我们可以...