【Java】【web】ServletContext

ServletContext

  1. 可获取全局配置信息
  2. 可获取当前应用任何位置的资源
  3. 域对象,在当前应用可以使多个servlet共享数据

域对象


public class ServletDemo6 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置ServletContext属性
        this.getServletContext().setAttribute("name", "张三");
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

// 读取设置
public class ServletDemo7 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = (String) this.getServletContext().getAttribute("name");
        System.out.println(name);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

获取全局配置




    servletDemo
    
    
    
        encoding
        UTF-8
    
    
    
    
        servletDemo
        com.demo.ServletDemo
        
        1
    
    
        servletDemo
        /demo1
    

// java
public class ServletDemo8 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String encoding = (String) this.getServletContext().getInitParameter(
                "encoding");
        System.out.println(encoding);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

请求向下转发

// 请求向下转发
public class ServletDemo9 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("这里是demo9");
        ServletContext app = this.getServletContext();
        // 将请求向下传递
        app.getRequestDispatcher("/demo10").forward(request, response);
        
        System.out.println("向下传递结束");
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

// 接收请求转发
public class ServletDemo10 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("这里是demo10");
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

你可能感兴趣的:(【Java】【web】ServletContext)