码迷,mamicode.com
首页 > 其他好文 > 详细

ServletContext中的转发

时间:2015-08-03 18:47:25      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

客户端向服务器发送请求,服务器将请求进行转发,获得响应信息,客户端只发送一次请求,地址栏信息不变。

服务器接收类,进行转发

package com.itheima.zhuanfa;

import java.io.IOException;

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

public class ServletContextDemo3 extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
//		转发
		//获得ServletContext对象
		ServletContext sc=getServletContext();
		System.out.println("转发前");
		resp.getOutputStream().write("before".getBytes());
		//获得转发器
		RequestDispatcher rd=sc.getRequestDispatcher("/Demo4");//得到请求转发器
		rd.forward(req,resp);
		/*
		 * 转发的特点:请求的地址栏不变,两者共享request和response对象
		 * 转发前和转发后的页面输出都不会发送到客户端
		 * 转发前不要刷新response中的内容,会吧response中的内容清空
		 */
		System.out.println("转发后");
		resp.getOutputStream().write("after".getBytes());
		

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	}

}

 转发到的类把这个类的信息传到客户端

package com.itheima.zhuanfa;

import java.io.IOException;

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

public class ServletContextDemo4 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.getOutputStream().write("转发成功,我来自Demo4".getBytes());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	}
	
}

 

ServletContext中的转发

标签:

原文地址:http://www.cnblogs.com/lzzhuany/p/4699720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!