2005-6-10 星期五 晴
参考:孙卫琴 《精通Struts:基于MVC的Java Web设计与开发》
Web组件间存在三种关联关系:
- 请求转发
- URL重定向
- 包含
请求转发:
所谓的“请求转发”,就是转发“请求”。在HTTP Web中“请求”=“request”。所以请求转发,其实是一个request<-->response的问题。转发的范围是“同一个web应用”。简单的说就是yahoo的登陆不能“转发(登陆)”到sohu的页面。请求从源组件转发到目标组件,目标组件进行处理后在转发回给目标组件。
web client--->Servlet controller--->JSP(destination component) @
web client (view)<-----------JSP(destination component) @
转发源组件和目标组件在request范围内共享数据。
在Servlet中通过 javax.servlet.RequestDispatcher.forward( )方法来进行请求转发。
J2EE的API document是这样描述RequestDispatcher Interface的:
Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
简单示例:
RequestDispatcher rd = request.getRequestDispatcher("destination component");
//Forward to requested URI
rd.forward(request,response);
在Jsp中通过标签<jsp:forward page="destination component">进行请求转发。
重定向:
重定向类似请求转发,但是他们之间却又有本质的区别:
- URL重定向可以定向到任何URL,不一定是“同一web应用”,比如yahoo上的链接,链接到sohu上的新闻。
- 重定向的源组件和目标组件不共享request数据,这个也是同请求转发的本质区别。
在servlet中通过sendRedirect( )方法来重定向:
request.sendRedirect( URL );
包含(略讲):
引用《精通struts...》:包含关系允许一个web组件聚集来自同一个web应用中其他web组件的输出数据,并使用被聚集的数据来创建响应结果。
如jsp标签<jsp:include page="title.jsp">
但是要注意jsp标签同include指令之间的区别
<% include file="title.jsp"%>
<jsp:include page="">可以包含动态文件,而include指令不行。
include指令include的文件已经编译就不能改变了,
但是<jsp:include>则不一样,它可以动态的向被包含的文件中传递参数:
<jsp:include page="test.jsp">
<jsp:param name="name" value="tomkoo"/>
</jsp>
总结:
本文主要上我的一点学习心得,搞了这么久的web应用,居然最近才彻底搞清楚请求转发和重定向,汗颜!!!!
本文介绍了Web组件间的三种关联关系:请求转发、URL重定向和包含。请求转发在同一web应用内,源和目标组件共享request数据;重定向可到任意URL,源和目标组件不共享request数据;包含可聚集其他组件输出数据,<jsp:include>能包含动态文件并传参。
232

被折叠的 条评论
为什么被折叠?



