Request_共享数据(域对象)以及获取ServletContext
Request_共享数据(域对象)以及获取ServletContext
域对象:一个有作用范围的对象,可以在范围内共享数据
request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
方法:
void setAttribute(String name,Object obj):存储数据
Object getAttitude(String name):通过键获取值
void removeAttribute(String name):通过键移除键值对
@WebServlet(name = "RequestDemo8", value = "/RequestDemo8") public class RequestDemo8 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("demo8....被访问了"); //转发到demo9资源 /*RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestDemo9"); requestDispatcher.forward(request, response);*/ //存储数据到request域中 request.setAttribute("msg", "hello"); //链式编程 request.getRequestDispatcher("/RequestDemo9").forward(request, response); } }
@WebServlet(name = "RequestDemo9", value = "/RequestDemo9") public class RequestDemo9 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取数据 Object msg = request.getAttribute("msg"); System.out.println(msg); System.out.println("demo9....也被访问了"); } }
获取ServletContext
ServletContext getServletContext();
@WebServlet(name = "RequestDemo10", value = "/RequestDemo10") public class RequestDemo10 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext ServletContext servletContext = request.getServletContext(); System.out.println(servletContext); } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本