论坛首页 Java企业应用论坛

Servlet中的forward

浏览 1787 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-03-05  

众所周知,forward是常用页面重定向方式之一。以前对于forward认知,仅限于可用阶段和理解它与sendRedirect的区别。使用时,几乎每次都是可耻的copy现有代码,未从深究过forward来龙去脉。

直到最近forward的使用过程中遇到了一个路径问题,正好得空,就此略微深入了解一番。

首先来看forward常用方式:

 

request.getRequestDispatcher(path).forward(request,response);

其实稍微一深究,就会有几个疑问:

1、getRequestDispatcher出来的究竟是神马对象?它还有什么其他用途?还有其它获取方式没有?

2、path是否为相对路径?

RequestDispatcher对象(详细可参考Servlet规范中的SRV.8节ServletAPI

查看相关文档之后,答案其实很简单:

顾名思义,它起到requst的分发作用。除了Request对象中获取,还可以从ServletContext对象中获取

 

this.getServletContext().getRequestDispatcher

关于路径问题,servlet spec有这么一段解释:

The behavior of this method is similar to the method of the same name in the
ServletContext. The servlet container uses information in the request object to
transform the given relative path against the current servlet to a complete path.

简单来理解,request对象中获取的,容器会根据request上来的路径进行相对路径的处理,所以request对应的获取方法支持相对路径。然而ServletContext对应的获取方法只支持绝对路径。

在tomcat中,在ServletContext.getRequestDispatcher方法中使用相对路径,得到以下异常:

 

 

java.lang.IllegalArgumentException: Path f.htm does not start with a "/" character
	org.apache.jsp.wap20.forward_jsp._jspService(forward_jsp.java:43)
	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

 而在resin中,也有类似的异常:

 

java.lang.IllegalArgumentException: request dispatcher url 'f.htm' must
be absolute

 答案显而易见了。

除了forward方法,RequestDispatcher对象还有一个include方法,作用跟jsp中的<%@ include file="path" %>一样,应该是为了在servlet中使用。

 

 

 

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics