javaweb之request请求转发forward方法的细节

package test.request;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//request请求转发时forward方法的细节,客户端只发一次请求,而服务器端有多个资源调用,地址栏不会发生变化
/*
 * 	1.	forward方法用于将请求转发到RequestDispatcher对象封装的资源,
 *	2.	如果在调用forward方法之前,在servlet程序中写入的部分内容已经被真正的传送到了客户端(调用了flush或者close方法),
 *		forward方法将抛出IllegalStateException异常
 *	3.	如果在调用forward方法之前向Servlet引擎的缓冲区(response)中写入了内容,
 *		只要写入到缓冲区的内容还没有被真正输出到客户端,forward方法就可以被正常执行,
 *		原来写入到缓冲区中的内容将被清空,但是,以写入到HttpServletResponse对象中的响应头字段信息保持有效
 */
public class RequestDemo6 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test3(request, response);
	}
	//细节3
	private void test3(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String date = "aaaaaa";
		PrintWriter print = response.getWriter();
		print.write(date);
		//以下代码不会出现问题,但是上面的date是不能在页面输出的,页面中只能看见index.jsp的内容
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
	//细节2,转发了好多次,避免这个问题,forward之后要return
	private void test2(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String date = "aaaaaa";
		if(true) {
			//几百行代码
			request.getRequestDispatcher("/index.jsp").forward(request, response);
			//return;   //跳转之后一定要记得return
		}
		//几百行代码
		// 以下代码将出现:java.lang.IllegalStateException: Cannot forward after response has been committed
		//上面已经转发一次了
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
	//细节2
	private void test1(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String date = "aaaaaa";
		PrintWriter print = response.getWriter();
		print.write(date);
		print.flush();//print.close();
		// 以下代码将出现:java.lang.IllegalStateException: Cannot forward after response has been committed
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


index.jsp就是一个最原始的jsp页面

你可能感兴趣的:(自己用)