共计 2677 个字符,预计需要花费 7 分钟才能阅读完成。
3. 共享数据:* 域对象:一个有作用范围的对象,可以在范围内共享数据
* request 域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
* 方法:1. void setAttribute(String name,Object obj): 存储数据
2. Object getAttitude(String name): 通过键获取值
3. void removeAttribute(String name): 通过键移除键值对
package cn.itcast.web.request;
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.Enumeration;
import java.util.Map;
import java.util.Set;
@WebServlet(“/requestDemo7”)
public class RequestDemo7 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 设置流的编码
request.setCharacterEncoding("utf-8");
// 获取请求参数 username
String username = request.getParameter("username");
System.out.println(username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);
}
}
package cn.itcast.web.request;
import javax.servlet.RequestDispatcher;
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;
@WebServlet(“/requestDemo8”)
public class RequestDemo8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("demo8888 被访问了。。。");
// 转发到 demo9 资源
/*
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestDemo9");
requestDispatcher.forward(request,response);
*/
// 存储数据到 request 域中
request.setAttribute("msg","hello");
request.getRequestDispatcher("/requestDemo9").forward(request,response);
//request.getRequestDispatcher("http://www.itcast.cn").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);
}
}
package cn.itcast.web.request;
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;
@WebServlet(“/requestDemo9”)
public class RequestDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取数据
Object msg = request.getAttribute("msg");
System.out.println(msg);
System.out.println("demo9999 被访问了。。。");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);
}
}