ServletContext

servletContxt是Web的四大作用域中最大的,他的范围为整个web项目,ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭,其才释放。
ServletContext
ServletContext

1.共享数据

HelloServlet:放数据

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context=this.getServletContext();

        String username="卡卡";
        context.setAttribute("username",username);//将一个数据保存在ServletContext中
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

GetServlet:取数据

public class GetServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context=this.getServletContext();
        String username= (String)context.getAttribute("username");

        //解决中文乱码问题
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().print("名字:"+username);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml的配置:

<servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kakafa.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kakafa.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>
上一篇:HttpServletResponse


下一篇:Java web 四