---
title: "小议Servlet中的RequestDispatcher与forward"
author: "lanceverw"
date: "2012-10-10T18:04:20Z"
tags: ["JavaEE", "Servlet"]
categories: ["编程语言"]
slug: "servlet-requestdispatcher-forward"
draft: false
lastmod: "2012-10-10T18:04:20Z"
id: 1695278
url: "https://lanceverw.iteye.com/blog/1695278"
---

最近复习Servlet一些相关知识，看到我们可以使用两种方式获取RequestDispatcher，即

```
//从ServletContext对象获取
getServletContext().getRequestDispatcher(String path).forward(req, resp);

//从Request对象获取
request.getRequestDispatcher(String path).forward(req, resp);
```

 

这两种方式都能具有forward方法，它们有什么区别呢？在网上查了查相关资料以供参考。

在stackoverflow上有人给出了这样的解释：

If you use absolute path ("/index.jsp"), there is no difference.

If you use relative path, you must use HttpServletRequest.getRequestDispatcher(). ServletContext.getRequestDispatcher() doesn't allow it.

For example, if you receive your request on http://example.com/myapp/subdir,

RequestDispatcher dispatcher =  
request.getRequestDispatcher("index.jsp);  
dispatcher.forward( request, response );

Will forward the request to the page http://example.com/myapp/subdir/index.jsp.

In any case, you can't forward request to a resource outside of the context.

 

简单的翻译下以上的答案：

1\. 如果使用绝对地址，如 /index.jsp这种方式，二者无区别；

2\. 如果使用相对地址，你只能使用request.getRequestDispatcher, ServletContext不允许使用相对路径；

3\. 任何情况下你都不能将转发地址指向context之外的地方。

 

在实际使用过程中还有两点需要注意：

1\. 在forward之前，不允许使用PrintWriter向页面输出内容（这里我自己测试了下，在forward之前向页面输出内容可能导致页面不会正确跳转）。

2\. foward语句跳转后，可利用return或抛出异常的方式来结束当前servlet。