4.1 Request域
有效范围
一次请求内有效,请求转发时数据可以传递,除此之外该域没有办法实现数据共享
生命周期
创建 每发生一次请求创建一个独立的请求域
使用service方法中或者请求转发有效
销毁 请求结束,已经向浏览器响应数据
测试代码
向request域中放入数据
package com.msb.testRequest;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */@WebServlet(urlPatterns = "/addToRequest.do")public class Servlet1 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 向request域中添加数据 List<String> x=new ArrayList<>(); Collections.addAll(x, "a","b","c"); req.setAttribute("list", x); req.setAttribute("gender","boy"); req.setAttribute("gender","girl"); req.setAttribute("name","晓明"); // 请求转发 req.getRequestDispatcher("/readFromRequest.do").forward(req,resp); // 重定向 //resp.sendRedirect("readFromRequest.do"); }}
request域中读取数据
package com.msb.testRequest;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.List;/** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */@WebServlet(urlPatterns="/readFromRequest.do")public class Servlet2 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 移除域中的互数据 req.removeAttribute("gender"); // 从request域中读取数据 List<String> list =(List<String>) req.getAttribute("list"); System.out.println(list); System.out.println(req.getAttribute("gender")); System.out.println(req.getAttribute("name")); //获取Request中的请求参数 System.out.println(req.getParameter("username")); System.out.println(req.getParameter("password")); }}