首页 > 其他分享 >Request_共享数据(域对象)以及获取ServletContext

Request_共享数据(域对象)以及获取ServletContext

时间:2022-12-04 20:35:03浏览次数:43  
标签:Request void request HttpServletResponse ServletContext Override 共享 response

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);
    }
}

 

运行结果:

 

标签:Request,void,request,HttpServletResponse,ServletContext,Override,共享,response
From: https://www.cnblogs.com/qihaokuan/p/16950610.html

相关文章