admin 管理员组

文章数量: 887021


2024年1月13日发(作者:mq消息中间件面试题)

中英文对照外文翻译文献

(文档含英文原文和中文翻译)

译文:

Web 2.0下的Spring MVC框架

摘要 - 当要建立丰富用户体验的WEB应用时,有大量的WED应用框架可以使用,却很少有该选择哪一种的指导。WEB 2.0应用允许个体管理他们自己的在线网页,并能与其他在线用户和服务器共享。这样分享需要访问控制器来实现。然而,现有的访问控制器解决方案不是令人很满意。因为在开放且由用户主导的WEB环境下,它满足不了用户的功能需求。MVC框架是在所有的WEB开发框架中最受欢迎的。模型-视图-控制

器(MVC)是一种软件架构,如今被认为是一种体系结构在软件工程模式中使用。该模式从用户界面(输入和演示)分离出了“领域逻辑”(基于用户的应用逻辑),它允许独立地开发,测试和维护每个分离的部分。模型-视图-控制器(MVC)模型创建的应用分离为不同的层次应用,同时在每两者之间建立松散的耦合。

关键字 - Spring MVC, 结构, XStudio, SOA, 控制器

I.绪论

如何确切地定义一个网站为“WEB 2.0”的呢?关于这有着许多不同见解,使它很难精确地下一个确切的定论。但当我们将所有的WEB开发框架过一遍之后它就会变得清晰了。各种基于WEB开发的架构如下:

 Ntier架构(Ntier Architecture)

在软件工程中,多层架构(常被称为n-tier架构)是一种表示层,应用处理层和数据管理层在逻辑上分开处理的客户端-服务器架构。例如,一个应用在用户与数据库之间使用中间件提供数据请求服务就用到了多层体系结构。最为广泛应用的多层体系结构是三层架构。N-tier应用架构为开发者提供了用来创建了一个灵活且可复用的模型。通过打破应用层次,开发者只需修改或添加一个特定的层,而不是要去重写一遍整个应用。它需要有一个表示层,一个业务层或者数据访问层和一个数据层。层(layer)和层(tier)之间的概念常常是可以互换的。

 服务导向架构(Service Oriented Architecture)

在软件工程中,服务导向架构(SOA)是一套原则,是一种软件设计开发的方法,基于以可互操作服务形式。这些服务是明确的业务功能,由可重用于不同方面的软件组件(离散代码块和/或数据结构)组成。SOA设计原则被应用到了系统开发和集成的各个阶段。SOA也普遍为消费者的服务提供了一种方式,如基于WEB的应用,以了解可用的基于SOA的服务。例如,一个公司的几个不同部门可能开发和部署了SOA服务在不同的实现语言;他们各自的客户通过访问公开,良好定义的接口能从中获益。XML经常用于SOA服务接口,即使它不是必要的。JSON也开始变得很常见。

 MVC架构(MVC Architecture)

MVC是来自Hyfinity的一种新生代的开发应用和集成工具。基于原生XML,MVC能够使企业规模、基于浏览器的应用快速的开发。为了快速组装完整的交互式应用程序,MVC提供了直观的图形化IDE(集成开发环境)。其中一个使MVC区别于大多数传统方法的关键是信息流的概念,它保留了所采集的基于文档的信息,通过数据绑定和路由校验。这些全部使用原生XML执行。

MVC使用XStudio来开发XML应用,使用XPlatform来运行产生的应用。MVC主要关注交互式自助应用的发展和使用包括以FromMaker闻名的XStudiio在内的工具来建立完整的WEB应用。

II. MVC架构

正如我们在之前章节所讨论的,普遍认为一个应用应有三个主要层次:表现层(UI),应用逻辑,和资源管理。在MVC中,表现层划分为

了控制器和视图。最重要的分隔在于表现层和应用逻辑之间。视图/控制器的分隔相对较少。MVC包含的不仅仅是架构的应用还有典型的设计模式。因此结构模式之类的术语可能被用到,再或者是集合设计模式。

 模型(Model)

以特定领域来表现应用操作的信息。模型是应用逻辑层(有时也叫做域层))的另一种称呼。应用(或域)逻辑丰富了原始数据的意义(例如,计算今天是否是用户生日,或者购物车中商品的总额,税和运费)。许多应用利用现有的存储机制(如数据库)来存储数据。MVC并没有特意提及资源管理层次,因为它被理解为底层的或者封装的模型。

 视图(View)

使模型渲染到表单适合于交互,典型的是一个用户的界面元素。在WEB应用中经常看到的MVC中,视图是HTML页面和为页面采集动态数据的代码。

 控制器(Controller)

处理和相应事件,尤其是用户actions,并且可能调用模型和视图的变化。

虽然MVC有不同的特性,控制流程一般如下:

1.用户以某种方式与用户界面进行交互(例如,用户按下一个按钮)。

2.一个控制器处理来自用户界面的输入事件,经常通过注册操作或回调。

3.控制器访问模型,可能采用适当用户的action方法来更新它

(例如,控制器更新用户的购物车)。复杂的控制器通常被设计使用命令模式封装action和简化继承。

4.一个视图使用模型来生成一个合适的用户界面(例如,视图产生一屏购物车内容的列表)。视图从模型中得到自己的数据。模型与视图没有直接关联。(然而,观察者模式可使模型间接通知相关方的变化,包括潜在的视图。)

5.用户界面等待进一步用户交互后开始新的循环。

以上数字概述的模型,视图和控制器之间的关系由基于以下。

A.实现策略

SpringMVC框架是基于分派请求操作的分发器(DispatcherServlet)设计的。有着可配置的处理器映射(handler mappings)、视图解析器(view resolution)、本地化(locale)和主题解析器(theme

resolution)同时支持上传文件。

MVC的特性

 明确分工。每个角色——控制器,校验器(validator),命令对象(command object),表单对象(form object), 模型对象(model object), 分发器,处理器映射, 视图解析器等等都有专门的对象来实现。

 将框架类和应用类作为JavaBeans的配置强大且直接明了。包括通过应用上下文配置中间层引用,例如从WEB控制器到业务对象和校验器。

 适用性,不受干扰性,和灵活性。根据给定场景,用一些参

数注解(例如:@RequestParam,@RequestHeader,@PathVariable,还有很多)来定义你需要的控制器方法。

 可复用业务代码,无需复制。使用已有的业务对象作为命令对象或者表单对象而不是通过映射来继承特殊的框架基类。

 可定制的绑定和校验。将类型不匹配作为应用级别校验错误,能保留值,本地化日期和数字绑定等,而不是使用需要手动解析并转换业务对象的且只是字符串的表单对象。

 可定制的处理器映射和视图解析器。处理器映射和视图解析器策略的范围从简单的基于URL的配置到复杂的专用解析策略。Spring比WEB MVC框架更加灵活在授权一个特定技术上看来。

 灵活的模型传输。模型传输是支持根据名字/值的Map,很容易集成任何视图的技术。

 可定制的本地化和主题解析,支持JSP,无论是否使用Spring标签库,支持JSTL,支持不需要额外过度的Velocity等等。

 一个简单且强大的JSP标签库称为Spring标签库,提供的功能如数据绑定和主题。定制标签允许最大程度的灵活性就标记代码而言。

 在Spring2.0中引入的一种JSP表单标签库能使在JSP界面中写表单更便捷。

 Beans的生命周期范围是当前HTTP请求或HTTP会话。它并不

是Spring MVC本身具体特征,而是Spring MVC使用了WebApplicationContext容器的。

图架构

C.可插拔性的其他MVC的实现

如果你不想使用Spring的WEB MVC,但打算使用Spring提供的其它功能,你可以很容易地将你选择的WEB MVC框架和Spring整合。直接通过Spring的Context-LoaderListener启动一个Spring根应用上下文,通过它的ServletContext属性(或者Spring的各种帮助方法)来访问来自Struts或者WebWork的action。没有"plugins"参与, 所以也没有针对它整合的必要。从WEB层的角度看,你只要使用Spring作为库,带有根应用上下文的实例作为切入点。

你所注册的beans和Spring的服务随时可访问及时在没有Spring的WEB MVC的情况下。Spring并没有在这种情景下与Struts或者WebWork竞争。它只是提供了纯WEB MVC框架在很多领域所不具备的,从bean配置到数据访问和事务处理。所以你可以用Spring中间层和/或数据访问层来丰富你的应用,及时你只是想使用,好比,JDBC和Hibernate这样的抽象事务管理。

Spring的WEB MVC框架同很多其他的WEB框架一样,是由请求驱动的。围绕着一个能将请求分发到控制器的servlet设计,它还提供其他有利于WEB应用开发的功能。然而Spring的分法器所做的不仅如此。它完整的整合了Spring Ioc容器使你能够使用Spring所具有的其他功能。

Spring Web MVC分发器的请求处理工作流在下方的图说明。模式理解阅读器会识别分发器是“前端控制器”设计模式的表达式(这是一种Spring WEB MVC与其他许多领先框架共享的模式)。

分发器是一个真正的Servlet(它继承至HttpServlet基础类),并同样要在你的web应用的文件中声明。你需要映射你想让分发器处理的请求,通过在同个文件中使用URL映射。这是标准的J2EEservlet配置。

...

example

cherServlet

1

example

*.form

在上面的例子中,所有以.form结尾的请求会被exampleDispatcherServlet处理。这只是配置Spring WEB MVC的第一步。你现在需要使用Spring Web MVC框架配置各种beans。当初始化一个分发器,框架会查找一个名为[servlet-name]-在你的Web应用的WEB-INF目录下并创建里面所定义的beans,重定义所有全局同名定义的beans。

图2.请求处理工作流

Spring分发器使用特有的beans来处理请求和显示相应的视图。这些beans就是Spring框架的一部分。你可以在WebApplicationContext中配置它们,配置方式就象配置其它bean的方式一样。然后,对于大多数bean来说,已经提供了合理的缺省配置,所以你最初不需要配置它们。

在你启动好分发器后,且有一个请求触发了指定的分发器,接下来分发器按以下步骤处理请求:

1.查找WebApplicationContext,并绑定该请求成为一个属性,使控制器和其他处理器在处理过程中能使用。缺省绑在分发器.WEB_APPLICATION_CONTEXT_ATTRIBUTE这个关键字上。

2.绑定本地化信息解析器到请求上,使处理过程中的处理器在处理请求(显示视图,准备数据等)时能解析本地化信息。如果你不需要本地化信息解析器,就忽视它。

3.绑定主题解析器到请求上,让视图之类的元素能决定使用哪个主题。如果你不需要主题,你可以忽视它。

4.如果你指定了多文件解析器,请求会被检测是否使用了multiparts;若是,请求会保存到MultipartHttpServletRequest中,以便处理过程中的其他处理器进一步处理。

5.查找合适的处理器。如果找到,为了准备模型数据或渲染视图,与该处理器(预处理器,后处理器,控制器)相关的执行链会被执行。

6.如果模型返回数据,就显示视图。否则,(可能由于安全因素,被前处理器或后处理器拦截了请求),无视图显示,因为请求已经被结束。

III. 控制器实现

Spring 2.5引入了基于注解的编程模型,MVC的控制器可以使用诸如@RequestMapping, @RequestParam, @ModelAttribute等注解。注解

能同时支持Servlet MVC和Portlet MVC。这种方式实现的控制器无需继承指定的基类或者实现指定的接口。而且,它们通常不直接依赖于Servlet或Portlet APIs,但你可以很配置访问到Servlet或Portlet设置。

@Controller

public class HelloWorldController {

@RequestMapping("/helloWorld")

public ModelAndView helloWorld() {

ModelAndView mav = new ModelAndView();

wName("helloWorld");

ect("message", "Hello World!");

return mav;

}

}

你能够看到,@Controller和@RequestMapping注解允许灵活的方法名和签名。在这上面的例子中的方法没有参数,返回一个ModelAndView,但还有其他各种(更好的)策略的存在,会在本章后面介绍。ModelAndView,@Controller,和@RequestMapping是Spring MVC实现的基础组成。这章节文档会介绍这些注解如何普遍的在Servlet中应用。

@Controller表明一个独有的类为一个控制器服务。Spring不要求你继承任何控制器的基类或引用Servlet API。然而,你仍能引用你需要的Servlet其他的功能。@Controller注解以固定注解类形式来表明它的角色。分发器就可以通过该注解来获取这个类中带有@RequestMapping注解的方法。你可以明确的注解控制器bean,通过在分发器上下文中使用标准的Spring bean定义。然而,@Controller模式也允许自动侦测,在类路径中匹配Spring的公共侦测组件类并为他们自动注册bean定义。要实现注解控制器自动探测,需要在配置文件中加入探测组件。

A.用@RequestMapping映射请求

使用@RequestMapping注解来映射就像/appointments这样的URLs到整个类或特定的处理方法。一般来说,类级别的注解映射特定的请求路径到表单控制器上,而方法级别的注解只是映射为一个特定的HTTP方法请求(“GET”,“POST”等)或HTTP请求参数。下这个例子显示了在Spring MVC应用中的一个控制器使用该注解:

@Controller

@RequestMapping("/appointments")

public class AppointmentsController {

private final AppointmentBook appointmentBook;

@Autowired

public AppointmentsController(AppointmentBook appointmentBook) {

tmentBook = appointmentBook;

}

@RequestMapping(method = )

Public Map get() {

return ointmentsForToday();

}

@RequestMapping(value="/{day}", method = )

public Map getForDay(@PathVariable

}

@RequestMapping(value="/new", method = )

public AppointmentForm getNewForm() {

return new AppointmentForm();

}

@RequestMapping(method = )

public String add(@Valid AppointmentForm appointment, BindingResult result){

if (ors()) {

}

ointment(appointment);

return "redirect:/appointments";

}

}

return "appointments/new";

return ointmentsForDay(day);

@DateTimeFormat(iso=) Date day, Model model) {

在例子中,@RequestMapping在多处使用到。第一种用法在类级别上,

表明该控制器中的所有处理方法与/appointments路径有关。get()方法进行进一步@RequestMapping细化配置:它只接受GET请求,也就意味着只有/appointments路径下的HTTP GET请求才调用该方法。post()方法有类似的细节,通过 getNewForm()方法与HTTP方法和路径的定义合而为一,/appointments

/new的GET请求能够处理该方法。

B.支持的处理方法参数和返回类型

@RequestMapping注解的处理方法拥有十分灵活的签名。大多数可以不按顺序的使用。

 请求或响应对象(Servlet API),选择任意指定的请求或响应类型,例如ServletRequest或HttpServletRequest。

 会话对象(Servlet API):HttpSession类型的。这种类型的参数强转成一个相应存在的session。所以,这样的参数绝不会为空。

 @PathVariable 注解方法参数并将其绑定到URI模板变量的值上。

 @RequestParam对访问指定Servlet请求的参数注解。参数值转化成方法中声明的类型。

 @RequestHeader对访问指定的Servlet的HTTP请求头参数注解。参数值转化成方法中声明的类型。

 ModelMap丰富了隐式模型,对于WEB视图是可见的。

 BindingResult 返回先前指令或表单对象的校验结果。

 标记处理完成的表单状态,会触发清理在处理器类型级别已被@SessionAttributes注解表明的会话属性。

接下来是处理器方法所支持的返回类型:

 一个ModelAndView对象,这个模式隐含指令对象和参考数据存取方法@ModelAttribute注解的结果。

 一个模型对象,视图名则通过RequestToViewNameTranslator把请求转换为视图名称。

 一个Map对象来表示模型,而视图名则利用RequestToViewNameTranslator把请求转换为视图名称。

 一个视图对象,该处理方法还可以以编程方式通过声明一个模型参数丰富模型(见上)。

 一个String对象来表示视图名,处理器中对于的方法也可以通过声明一个ModelMap的参数来表示model。

 空(void)表示方法自己处理响应(通过声明一个ServletResponse或HttpServlet-

Response直接输出响应内容)或者通过RequestToViewNameTranslator把请求转化为 视图名(此方法不用在处理方法中声明一个response参数)。

 其他任何的返回类型被当做一个单一的模型属性展示给视图,通过在方法级别指定@ModelAttribute来使用属性名(或基于返回类名的缺省属性名)。

IV. 视图

所有WEB应用的MVC框架都提供了访问视图的方法。Spring提供了视图解析器,使你提交模型到浏览器而无需绑定特定的视图技术。不同一般的,Spring允许你使用JSPs,Velocity模板和XSLT等多种视图。

Spring处理视图最重要的两个接口是ViewResolver和View。ViewResolver接口在视图名称和真正的视图之间提供映射;而View接口访问请求准备并提交请求给其中一种视图技术。

A.用视图解析器接口解析视图

在Spring WEB MVC处理器中所有处理器方法必须解析一个逻辑视图名,无论是显示的还是隐式的。Spring中的视图通过被视图解析器解析后的逻辑视图名来访问。Spring有很多视图解析器。

ResourceBundleViewResolver检查ResourceBundle定义下的bean名称,并解析每个视图。它用属性值[视图名].(class)作为视图类,属性值[视图名].url作为视图url。

B.视图重定向

正如先前提到的,一个控制器一般返回一个逻辑名,解析器再将其解析成特定的视图技术。对于如JSPs这样通过Servlet或JSP引擎来处理视图的技术来说,它的解决方案通常要结合InternalResourceViewResolver和InternalResourceView,通过d()方法或者

e() 方法发布内部转发或包含指令。对于其他诸如Velocity,XSLT的视图技术,视图本上直接输出内容到响应流。

有时在视图渲染前发布HTTP重定向指令返回客户端是会发生的,当一个控制器已经被POSTed的数据调用,并且响应已经委托给另一个控制器(例如成功提交表单)。在这种情况下,一个常规的内部转发将意味着其他控制器也可能会看到相同的POST数据,如果它与其他预期的数据混淆是个潜在的问题。消除用户多次提交表单的可能性是另一个显示结果前执行重定向的原因。在这种情况下,浏览器会先发送原始的POST;得到响应后重定向到不同的URL;最后浏览器会显示GET后来在重定向响应指定的URL。这样一来,从浏览器看来,当前页没有反射POST的结果而是GET的。最后影响用户没有办法通过刷新,偶然地重POST同样的数据。刷新出的是GET的结果页,不是重发的原POST数据。

C.重定向视图

控制器响应结果的一种强制重定向方法是该控制器创建并返回一个Spring的重定向视图实例。在这种情况下,分发器不能使用正常的视图解析机制。因为它已经转发给视图了,分发器只能知识视图去完成它的工作。

重定向发出direct()指令使其作为HTTP重定向返回客户端浏览器。所有的模型参数被作为HTTP查询参数。这意味着模型只能包含一个对象(通常字符串和对象会转化成一个字符串表示形式),能很好的转换成一个正文HTTP查询参数。

如果你使用了重定向视图并且视图是由控制器自身创建的,建议你配置重定向的URL注入到控制器,这样他没有写在控制器中却能根据视图名在上下文中配置。

D.重定向:前缀

当重定向视图很好的起作用时,如果控制器自身创建了重定向视图,事实上难免控制器知道一个重定向发生。这真的很不理想并且关系太紧密了。控制器不应该关注响应如何处理。通常只有在视图名被注入时它才开始操作。

特殊的重定向:前缀能让你完整上述问题。如果带有前缀的视图名返回时,UrlBasedView-Resolver(所有的基类)会识别出它当作一个重定向所需的特殊指示。剩下的视图名会被当作重定向的URL处理。

效果是相同的,如果控制器已返回重定向视图,但现在控制器本身能简单地依据逻辑视图名进行操作。如同 redirect:/my/response/的一个逻辑视图名会重定向当前相关的servlet上下文,而名为redirect:/some/arbitrary/会重定向到绝对路径的URL。最重要的是,只要像其他逻辑视图名一样注入重定向视图名到控制器,控制器不会意识到重定向的发生。

E.视图技术

Spring为JSP和JSTL提供了对拆箱即用的解决方案。在版本2.0中使用JSP和Spring We-b MVC时,Spring为处理表单提供了一套全面的数据绑定标签。每个标签提供了与HTML相对应的标签属性集的支持,使标签能熟悉且直观的使用。HTML自生成标签符合HTML 4.01/XHTML1.0规范。

不同于其他的表单/输入标签库,Spring的表单标签库整合了Spring Web MVC,通过标签能返问指令对象和关联控制器所处理的数据。表单标签使JSPs更容易开发,阅读和维护。

MVC框架的优点

 Spring提供了一条非常清晰的分割线在控制器,JavaBean模型和视图之间。

 Spring的MVC十分灵活。Spring MVC框架的每个部分随时可以插入配置你自己的接口。当然也提供便利的类作为继承的选择。

 Spring,同WebWork类似,提供和控制器一样的拦截器,使它很容易处理许多请求。

 Spring控制器同其他类一样通过IoC方式配置。使得它们更易于测试和Spring管理的其他对象完美整合。

 Spring MVC web层比Strurs web层更易于测试,由于避免了强制具体继承和直接依赖于分发器servlet的控制器。

 Spring有很好的业务层接口。

V. 3层架构架构

通讯

 3层:表现层不能直接和数据层通信,只能通过逻辑层(线性拓扑)

 MVC:所有层直接通信(三角拓扑)

用法

 3层:主要用于客户端,中间件和数据层各自独立运行的平台上

的web应用

MVC:从以往来看,用于运行在单一图形化的工作空间上的应用(应用于单独的平台作为模型2)

原文:

Spring MVC Framework for Web 2.0

Abstract - When building rich user experience web applications, an abundance of

web application frameworks is available and only little guidance for making the decision

which one to 2.0 applications allow individuals tomanage their content

online and to share it with other users

access control

and services on the Web. Such sharing requires

to be put in place. Existing access control solutions, however,

are unsatisfactory as they do not offer the functionality that users need in the open and

user-driven Web environment. Out of all those web development framework the most

popular is MVC Framework. Model–view–controller (MVC) is a software architecture ,

currently considered an architectural pattern used in software engineering. The pattern

isolates "domain logic" (the application logic for the user) from the user interface (input

and presentation), permitting independent development, testing and maintenance of each

(separation of concerns). Model View Controller (MVC) pattern creates applications that

separate the different aspects of the application (input logic, business logic, and UI

logic),while providing a loose coupling between these elements.

Key Word - Spring MVC, Architecture, XStudio, SOA,Controller.

I. INTRODUCTION

So exactly what defines a web site as being “Web 2.0”?There are many different

opinions on this,making it difficult to pinpoint an exact definition. But it will get clear

when we will go through all available web development s

architectures for web development are as follows

 Ntier Architecture

In software engineering, multi-tier architecture (often referred to as n-tier

architecture) is a client–server architecture in which the presentation, the application

processing, and the data management are logically separate processes.[6] For example,

an application that uses middleware to service data requests between a user and a

database employs multi-tier most widespread use of multi-tier

architecture is the three-tier architecture. N-tier application architecture provides a

model for developers to create a flexible and reusable application. By breaking

up an application into tiers, developers only have to modify or add a specific layer, rather

than have to rewrite the entire application over. There should be a presentation tier,

a business or data access tier, and a data tier. The concepts of layer and tier are often used

interchangeably.

 Service Oriented Architecture

In software engineering, a Service-Oriented Architecture (SOA) is

a setof principles and methodologies for designing and developing software in the form

of interoperableservices. These services are well- defined business functionalities

that are built as software components (discrete pieces of code and/or data structures) that

can be reused for different purposes. SOA design principles are used during

the phases of systems development and integration. SOA also generally provides a way

for consumers of services, such as web-based applications, to be aware

of available SOA-based services. For example, several disparate departments within a

company may develop and deploy SOA services in different implementation languages;

their respective clients will

access them.

benefit from a well-understood, well-defined interface to

XML is often used for interfacing with SOA

services, though this is not required. JSON is also becoming increasingly common.

 MVC Architecture

MVC is part of a new generation of application development and integration tools

from Hyfinity. Based on native XML, MVC enables the rapid development of

enterprise-scale browser-based applications. MVC provides intuitive graphical IDEs for

rapidly assembling complete interactive applications. One of the key differences between

MVC and more traditional approaches is the information flow concept that preserves

document-based information from capture, validation through to data binding and routing.

All of this is performed using native XML.

MVC uses XStudio for developing XML applications and XPlatform for hosting the

resulting applications. MVC is primarily concerned with the development of interactive

self-service applications and employs a tool within XStudio known as FormMaker for

building complete web applications.

II. MVC A RCHITECTURE

As we discussed in the previous section, it is common to think of an application as

having three main layers: presentation (UI), application logic, and resource management.

In MVC, the presentation layer is split into controller and view. The most important

separation is between presentation and application logic. The View/Controller split is less

so. MVC encompasses more of the architecture of an application than is typical for a

design pattern. Hence the term architectural pattern may be useful, or perhaps an

aggregate design pattern.

 Model

The domain-specific representation of the information on which the application

operates. The model is another name for the application logic layer (sometimes also

called the domain layer). Application (or domain) logic adds meaning to raw data (e.g.,

calculating if today is the user’s birthday, or the totals, taxes and shipping charges for

shopping cart items). Many applications use a persistent storage mechanism (such as a

database) to store data. MVC does not specifically mention the resource management

layer because it is understood to be underneath or encapsulated by the Model.

 View

Renders the model into a form suitable for interaction,typically a user interface

element. MVC is often seen in web applications, where the view is the HTML page and

the code which gathers dynamic data for the page.

 Controller

Processes and responds to events, typically user actions,and may invoke changes on

the model and view.

Though MVC comes in different flavours, the control flow generally works as

follows:

1. The user interacts with the user interface in some way (e.g., user presses a button).

2. A controller handles the input event from the user interface, often via a registered

handler or callback.

3. The controller accesses the model, possibly updating it in a way appropriate to the

user’s , controller updates user’s shopping cart).Complex controllers are often

structured using the command pattern to encapsulate actions and simplify extension.

4. A view uses the model to generate an appropriate user interface (e.g., view

produces a screen listing the shopping cart contents). The view gets its own data from the

model. The model has no direct knowledge of the view. (However, the observer pattern

can be used to allow the model to indirectly notify interested parties, potentially

including views, of a change.)

5. The user interface waits for further user interactions, which begins the cycle anew.

Above figure summarizes the relationship between the Model, View, and Controller

is provided below.

A. Implementation Strategy

The Spring Web model-view-controller (MVC)framework is designed around a

DispatcherServlet that dispatches requests to handlers, with configurable handler

mappings, view resolution, locale and theme resolution as well as support for uploading

files.

B. Features of Spring Web MVC

 Clear separation of roles. Each role -- controller, validator, command object,

form object, model object, DispatcherServlet, handler mapping, view resolver, and

so on can be fulfilled by a specialized object.

 Powerful and straightforward configuration of both framework and application

classes as JavaBeans. This configuration capability includes easy referencing across

contexts, such as from web controllers to business objects and validators.

 Adaptability, non-intrusiveness, and any controller method

signature you need,possibly using one of the parameter annotations(such as

@RequestParam, @RequestHeader,@PathVariable,and more) for a given scenario.

 Reusable business code, no need for existing business objects as

command or form objects instead of mirroring them to extend a particular framework

base class.

 Customizable binding and validation. Type mismatches as application-level

validation errors that keep the offending value, localized date and number binding,

and so on instead of String-only form objects with manual parsing and conversion to

business objects.

 Customizable handler mapping and view resolution. Handler mapping and view

resolution strategies range from simple URL-based configuration, to sophisticated,

purpose-built resolution strategies. Spring is more flexible than web MVC

frameworks that mandate a particular technique.

 Flexible model transfer. Model transfer with a name/value Map supports easy

integration with any view technology.

 Customizable locale and theme resolution, support for JSPs with or without

Spring tag library, support for JSTL, support for Velocity without the need for extra

bridges, and so on.

 A simple yet powerful JSP tag library known as the Spring tag library that

provides support for features such as data binding and themes. The custom tags

allow for maximum flexibility in terms of markup code.

Fig. 1. MVC Architecture

 A JSP form tag library, introduced in Spring 2.0,that makes writing forms in JSP

pages much easier.

 Beans whose lifecycle is scoped to the current HTTP request or HTTP Session.

This is not a specific feature of Spring MVC itself, but rather of the

WebApplicationContext container(s) that Spring MVC uses.

C. Pluggability of other MVC Implementation

If you do not want to use Spring's web MVC, but intend to leverage other solutions

that Spring offers, you can integrate the web MVC framework of your choice with Spring

start up a Spring root application context through its

ContextLoaderListener, and access it through its ServletContext attribute (or Spring's

respective helper method) from within a Struts or WebWork action. No "plug-ins" are

involved, so no dedicated integration is the web layer's point of view,

you simply use Spring as a library, with the root application context instance as the entry

point.

Your registered beans and Spring's services can be at your fingertips even without

Spring's Web MVC. Spring does not compete with Struts or WebWork in this scenario. It

simply addresses the many areas that the pure web MVC frameworks do not, from bean

configuration to data access nd transaction handling. So you can enrich your application

with a Spring middle tier and/or data access tier, even if you just want to use, for example,

the transaction abstraction with JDBC or Hibernate.

Spring's web MVC framework is, like many other web MVC frameworks,

request-driven, designed around a central servlet that dispatches requests to controllers

and offers other functionality that facilitates the development of web applications.

Spring's DispatcherServlet however, does more than just that. It is completely integrated

with the Spring IoC container and as such allows you to use every other feature that

Spring has.

The request processing workflowof the Spring Web MVC DispatcherServlet is

illustrated in the following diagram. The pattern-savvy reader will recognize that the

DispatcherServlet is an expression of the “Front Controller”design pattern (this is a

pattern that Spring Web MVC shares with many other leading web frameworks).

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base

class), [3] and as such is declared in the of your web application. You need to

map requests that you want the DispatcherServlet to handle, by using a URL mapping in

the same file. This is standard J2EE servlet configuration.

...

example

cherServlet

1

example

*.form

In the preceding example, all requests ending with .form will be handled by the

exampleDispatcherServlet. This is only the first step in setting up Spring Web MVC.

You now need to configure the various beans used by the Spring Web MVC framework.

Upon initialization of a DispatcherServlet, the framework looks for a file named

[servlet-name]- in the WEB-INF directory of your web application and creates

the beans defined there, overriding the definitions of any beans defined with the same

name in the global scope.

Fig. 2. Request Processing Workflow

The Spring DispatcherServlet uses special beans to process requests and render the

appropriate views. These beans are part of Spring Framework. You can configure them in the

WebApplicationContext, just as you configure any other bean. However, for most beans, sensible

defaults are provided so you initially do not need to configure them. These beans are described in

the following table.

After you set up a DispatcherServlet, and a request comes in for that specific

DispatcherServlet, the DispatcherServlet starts processing the request as follows:

1. The WebApplicationContext is searched for and bound in the request as an attribute that

the controller and other elements in the process can use. It is bound by default under the key

_APPLICATION_CONTE XT_ATTRIBUTE.

2. The locale resolver is bound to the request to enable elements in the process to resolve the

locale to use when processing the request (rendering the view,preparing data, and so on). If you

do not need locale resolving, you do not need it.

private final AppointmentBook appointmentBook;

@Autowired

public AppointmentsController(AppointmentBook appointmentBook) {

tmentBook = appointmentBook;

}

@RequestMapping(method = )

Public Map get() {

return ointmentsForToday();

}

@RequestMapping(value="/{day}", method = )

public Map getForDay(@PathVariable

}

@RequestMapping(value="/new", method = )

public AppointmentForm getNewForm() {

return new AppointmentForm();

}

@RequestMapping(method = )

public String add(@Valid AppointmentForm appointment, BindingResult result){

if (ors()) {

}

ointment(appointment);

return "redirect:/appointments";

}

}

return "appointments/new";

return ointmentsForDay(day);

@DateTimeFormat(iso=) Date day, Model model) {

3. The theme resolver is bound to the request to let elements such as views determine which

theme to use. If you do not use themes, you can ignore it.

4. If you specify a multipart file resolver, the request is inspected for multiparts; if

multiparts are found,the request is wrapped in a MultipartHttpServletRequest for further

processing by other elements in the process.

5. An appropriate handler is searched for. If a handler is found, the execution chain

associated with the handler (preprocessors, postprocessors, and controllers) is executed in order

to prepare a model or rendering.

6. If a model is returned, the view is rendered. If no model is returned, (may be due to a

preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is

rendered, because the request could already have been fulfilled.

III. I MPLEMENTING C ONTROLLER

Spring 2.5 introduced an annotation-based programming model for MVC controllers that uses

annotations such as @RequestMapping, @RequestParam, @ModelAttribute,and so on. This

annotation support is available for both Servlet MVC and Portlet MVC. Controllers implemented in

this style do not have to extend specific base classes or implement specific interfaces. Furthermore,

they do not usually have direct dependencies on Servlet or Portlet APIs, although you can easily

configure access to Servlet or Portlet facilities. As you can see, the @Controller and

@RequestMapping annotations allow flexible method names and signatures. In this particular

example the method has no parameters and returns a ModelAndView, but various other (and better)

strategies exist, as are explained later in this section. ModelAndView, @Controller, and

@RequestMapping form the basis for the Spring MVC implementation. This section documents these

annotations and how they are most commonly used in a Servlet environment.

@Controller

public class HelloWorldController {

@RequestMapping("/helloWorld")

public ModelAndView helloWorld() {

ModelAndView mav = new ModelAndView();

wName("helloWorld");

ect("message", "Hello World!");

**************************************************************************************does not require you to extend any controller base class or reference the Servlet API. However, you

can still reference Servlet-specific features if you need to. The @Controller annotation acts as a

stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for

mapped methods and detects @RequestMapping annotations. You can define annotated controller

beans explicitly, using a standard Spring bean definition in the dispatcher's context. However, the

@Controller stereotype also allows for auto detection, aligned with Spring general support for

detecting component classes in the classpath and auto-registering bean definitions for them. To enable

auto detection of such annotated controllers, you add component scanning to your configuration.

A. Mapping Requests with @RequestMapping

You use the @RequestMapping annotation to map URLs such as /appointments onto an entire

class or a particular handler method. Typically the class-level annotation maps a specific request path

(or path pattern) onto a form controller,with additional method-level annotations narrowing the

primary mapping for a specific HTTP method request method ("GET"/"POST") or specific HTTP

request parameters.

The following example shows a controller in a Spring MVC application that uses this annotation:

Intheexample,**************************************************************type (class) level,which indicates that all handling methods on this controller are relative to the

/appointments path. The get() method has a further @RequestMapping refinement: it only accepts

GET requests, meaning that an HTTP GET for /appointments invokes this method. The post() has a

similar refinement, and the getNewForm() combines the definition of HTTP method and path into one,

so that GET requests for appointments/neware handled by that method.

B. Supported Handler Methods arguments and Return Types

Handler methods that are annotated with @RequestMapping can have very flexible signatures.

Most of them can be used in arbitrary order

 Request or response objects (Servlet API). Choose any specific request or response type, for

example ServletRequestor HttpServletRequest.

 Session object (Servlet API): of type HttpSession. An argument of this type enforces the

presence of a corresponding session. As a consequence, such an argument is never null.

 @PathVariable annotated parameters for access to URI template variables.

 @RequestParam annotated parameters for access to specific Servlet request parameters.

Parameter values are converted to the declared method argument type.

 @RequestHeader annotated parameters for access to specific Servlet request HTTP headers.

Parameter values are converted to the declared method argument type.

 ModelMap for enriching the implicit model that is exposed to the web view.

 BindingResult validation results for a preceding command or form object.

 Status handle for marking form processing as complete, which triggers the cleanup of

session attributes that have been indicated by the @SessionAttributes annotation at the

handler type level.

The following return types are supported for handler methods:

 A ModelAndView object, with the model implicitly enriched with command objects and the

results of @ModelAttribute annotated reference data accessor methods.

 A Model object, with the view name implicitly determined through a

RequestToViewNameTranslator and the model implicitly enriched with command objects

and the results of @ModelAttribute annotated reference data accessor methods.

 A Map object for exposing a model, with the view name implicitly determined through a

RequestToViewNameTranslator and the model implicitly enriched with command objects

and the results of @ModelAttribute annotated reference data accessor methods.

 A View object, with the model implicitly determined through command objects and

@ModelAttribute annotated reference data accessor methods. The handler method may also

programmatically enrich the model by declaring a Model argument (see above).

 void if the method handles the response itself (by writing the response content directly,

declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if

the view name is supposed to be implicitly determined through a

RequestToViewNameTranslator (not declaring a response argument in the handler method

signature).

 Any other return type is considered to be a single model attribute to be exposed to the view,

using the attribute name specified through @ModelAttribute at the method level (or the

default attribute name based on the return type class name). The model is implicitly

enriched with command objects and the results of @ModelAttribute annotated reference

data accessor methods.

IV. V IEWS

All MVC frameworks for web applications provide a way to address views. [5] Spring provides

view resolvers, which enable you to render models in a browser without tying you to a specific view

technology. Out of the box, Spring enables you to use JSPs, Velocity templates and XSLT views, for

example.

The two interfaces that are important to the way Spring handles views are ViewResolver and

View. The ViewResolver provides a mapping between view names and actual views. The View

interface addresses the preparation of the request and hands the request over to one of the view

technologies.

A. Resolving Views with the ViewResolver Interface

All handler methods in the Spring Web MVC controllers must resolve to a logical view name,

either explicitly or implicitly. Views in Spring are addressed by a logical view name and are resolved

by a view resolver. Spring comes with quite a few view resolvers. This table lists most of them; a

couple of examples follow.

The ResourceBundleViewResolver inspects the ResourceBundle identified by the basename, and

for each view it is supposed to resolve, it uses the value of the property [viewname].(class) as the

view class and the value of the property [viewname].urlas the view url.

B. Redirecting To Views

As mentioned previously, a controller typically returns a logical view name, which a view

resolver resolves to a particular view technology. For view technologies such as JSPs that are

processed through the Servlet or JSP engine,this resolution is usually handled through the

combination of InternalResourceViewResolver and InternalResourceView,which issues an internal

forward or include via the Servlet API's d(..) method or

e() method. For other view technologies, such as Velocity, XSLT, and so on,

the view itself writes the content directly to the response stream.

It is sometimes desirable to issue an HTTP redirect back to the client, before the view is rendered.

This is desirable,for example, when one controller has been called with POSTed data, and the

response is actually a delegation to another controller (for example on a successful form submission).

In this case, a normal internal forward will mean that the other controller will also see the same POST

data, which is potentially problematic if it can confuse it with other expected data. Another reason to

perform a redirect before displaying the result is to eliminate the possibility of the user submitting the

form data multiple times. In this scenario, the browser will first send an initial POST; it will then

receive a response to redirect to a different URL; and finally the browser will perform a subsequent

GET for the URL named in the redirect response. Thus, from the perspective of the browser, the

current page does not reflect the result of a POST but rather of a GET. The end effect is that there is

no way the user can accidentally re-POST the same data by performing a refresh forces a

GET of the result page, not a resend of the initial POST data.

C. Redirect View

One way to force a redirect as the result of a controller response is for the controller to create and

return an instance of Spring'sRedirectView. In this case, DispatcherServlet does not use the normal

view resolution mechanism. Rather because it has been given the (redirect) view already, the

DispatcherServletsimply instructs the view to do its work.

TheRedirectView issues an HttpServletResponse-sendRedirect() call that returns to the client

browser as an HTTP redirect. All model attributes are exposed as HTTP query parameters. This means

that the model must contain only objects (generally Strings or objects converted to a String

representation), which can be readily converted to a textual HTTP query parameter.

If you use RedirectView and the view is created by the controller itself, it is recommended that

you configure the redirect URL to be injected into the controller so that it is not baked into the

controller but configured in the context along with the view names.

D. The redirect: prefix

While the use of RedirectView works fine, if the controller itself creates the RedirectView, there

is no avoiding the fact that the controller is aware that a redirection is happening. This is really

suboptimal and couples things too tightly. The controller should not really care about how the

response gets handled. In general it should operate only in terms of view names that have been

injected into it.

The special redirect: prefix allows you to accomplish this. If a view name is returned that has the

prefix redirect:, the UrlBasedViewResolver (and all subclasses) will recognize this as a special

indication that a redirect is needed. The rest of the view name will be treated as the redirect URL.

The net effect is the same as if the controller had returned a RedirectView, but now the controller

itself can simply operate in terms of logical view names. A logical view name such as

redirect:/my/response/ will redirect relative to the current servlet context, while a name

such as redirect:/some/arbitrary/ will redirect to an absolute URL. The

important thing is that, as long as this redirect view name is injected into the controller like any other

logical view name, the controller is not even aware that redirection is happening.

E. View Technologies

Spring provides a couple of out-of-the-box solutions for JSP and JSTL views. As of version 2.0,

Spring provides a comprehensive set of data binding-aware tags for handling form elements when

using JSP and Spring Web MVC. Each tag provides support for the set of attributes of its

corresponding HTML tag counterpart, making the tags familiar and intuitive to use. The tag-generated

HTML is HTML 4.01/XHTML1.0 compliant.

Unlike other form/input tag libraries, Spring's form tag library is integrated with Spring Web

MVC, giving the tags access to the command object and reference data your controller deals with. The

form tags make JSPs easier to develop, read and maintain.

Advantages of MVC Framework

 Spring provides a very clean division between controllers, JavaBean models, and views.

 Spring’s MVC is very flexible. just about every part of the Spring MVC framework is

configurable via plugging in your own interface. Of course we also provide convenience

classes as an implementation option.

 Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor

out behavior common to the handling of many requests.

 Spring Controllers are configured via IoC like any other objects. This makes them easy to

test, and beautifully integrated with other objects managed by Spring.

 Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance

of forced concrete inheritance and explicit dependence of controllers on the dispatcher

servlet.

 Spring has a well-defined interface to business layer

V. 3-T IER A RCHITECTURE V S . MVC A RCHITECTURE

Communication

 3-tier: The presentation layer never communicates directly with the data layer-only through

the logic layer (linear topology)

 MVC: All layers communicate directly (triangle opology)

Usage

 3-tier: Mainly used in web applications where the client, middleware and data tiers ran on

physically separate platforms

 MVC: Historically used on applications that run on a single graphical workstation (applied

to separate platforms as Model 2)

谢谢下载,祝您生活愉快!


本文标签: 视图 控制器 应用 请求 使用