1.request是一个域对象,具备以下方法

  setAttribute(string name,Object O)

  getAttribute(String name)

  removeAttribute( String name)

 

2.关于域对象的请求转发

servlet1,servlet2

        // 1.servlet1将请求转发给servlet2
        // 这是在服务器内部的请求(在web15内的请求不需要写为/WEB15/servlet2)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");
        // 2.执行转发的方法
        requestDispatcher.forward(request, response);

 

3.域对象中的数据转发

  servlet1   
         //向request域中存储数据  
        //request域的作用范围  在一次request和response请求中
        request.setAttribute("name", "Tom");   
 
  servlet2       
         //在request域中提取数据
        Object attribute = request.getAttribute("name");
        response.getWriter().write("hello word......"+attribute);              

 

4.注意事项

request域的作用范围:仅在一次request和response请求中有效

 

 

5.完整代码

servle1

package com.hdh.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域的作用范围  在一次request和response请求中
        request.setAttribute("name", "Tom");
        
        
        // 1.servlet1将请求转发给servlet2
        // 这是在服务器内部的请求(在web15内的请求不需要写为/WEB15/servlet2)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");
        // 2.执行转发的方法
        requestDispatcher.forward(request, response);

    }

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

}

 

servlet2

package com.hdh.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域的作用范围  在一次request和response请求中
        request.setAttribute("name", "Tom");
        
        
        // 1.servlet1将请求转发给servlet2
        // 这是在服务器内部的请求(在web15内的请求不需要写为/WEB15/servlet2)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");
        // 2.执行转发的方法
        requestDispatcher.forward(request, response);

    }

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

}

 

posted on 2018-10-22 15:45  忆夏KhaZix  阅读(533)  评论(0编辑  收藏  举报