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

黑马day04 request&请求转发

时间:2015-06-18 15:23:21      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:servlet

到此为止:已经学习了两个域对象:

servletContext:web应用

request:仅仅用于同一个请求

        作用范围:整个请求链上
        生命周期:当服务器收到一个请求,创建出代表请求的request对象,request开始.当请求结束,服务器销毁代表请求的request对象,request域结束.
        作用:在整个请求链范围内共享数据,通常我们在Servlet中处理好的数据会存入request域后请求转发到jsp页面来进行展示
        
        setAttribute
        getAttribute
        removeAttribute

1.下面的例子既使用了域对象也使用了请求转发Demo1(在request中放了一个对象)转发到Demo2

package cn.itheima.request;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 请求转发
 * @author Administrator
 *
 */
public class Demo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setAttribute("description", "李卫康--哈哈好自恋");
		request.getRequestDispatcher("/servlet/Demo2").forward(request, response);
	}

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


}

2.在Demo2中取出request域中的值并输出打印到浏览器中...

package cn.itheima.request;

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 Demo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String str = (String) request.getAttribute("description");
		response.getWriter().write(str);
	}

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

}

技术分享


黑马day04 request&请求转发

标签:servlet

原文地址:http://blog.csdn.net/u014010769/article/details/46547857

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