ServletContext域

ServletContext对象

往context域中存东西并把他取出来

继承HTTPServlet
image
覆盖方法
alt + insert
image


image
HelloServlet类

//两个类继承同一个方法
public class HelloServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //username赋值
        String username = "小红";
        //shuzi赋值
        int shuzi = 1;
        //往context域中存一个username
        context.setAttribute("username",username);
        context.setAttribute("shu",shuzi);



    }
}

HelloServlet类

//继承方法
public class HellServlet extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html;charset=utf-8");
        System.out.println("hello");
        //获得context
        ServletContext context = this.getServletContext();
        //从context域中取出username
        String username = (String) context.getAttribute("username");
        //强转为string类型,
         String username = "小红"
        Integer shu = (Integer) context.getAttribute("shu");
        //int类型
        response.getWriter().println(username);
        response.getWriter().print(shu);
    }


}

posted @ 2022-07-19 16:48  笑到肚子疼  阅读(29)  评论(0)    收藏  举报