欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

request域对象和请求转发

程序员文章站 2022-06-16 11:17:28
...

request域对象和请求转发

 

request的其他功能

request是一个域对象

request对象也是一个存储数据的区域对象,所以也具有如下方法:

setAttribute(String name, Object o)

getAttribute(String name)

removeAttribute(String name)

注意:request域的作用范围:一次请求中

request完成请求转发

获得请求转发器----path是转发的地址

RequestDispatcher getRequestDispatcher(String path)

通过转发器对象转发

requestDispathcer.forward(ServletRequest request, ServletResponse response)

package com.content.forward;

import java.io.IOException;

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

public class Servlet1 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//想request域中存储数据
		request.setAttribute("name", "tom");
		
		
		//servlet1 将请求转发给servlet2
		RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");
		//执行转发的方法
		dispatcher.forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
package com.content.forward;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//从request域中取出数据
		Object attribute = request.getAttribute("name");
		
		response.getWriter().write("hello haohao..."+attribute);
	}

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

 

相关标签: request