用ServletContext简单实现共享数据

public class test01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = "小明";
        context.setAttribute("username", username);

    }

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

用getServletContext方法得到ServletContext对象,并且用setAttribute() 将数据进行存储

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().println( "姓名:" + username);

    }

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

用getAttribute()方法拿到存储的数据,然后在配置Servlet和Servlet的映射

启动服务就可以在浏览器中进行展示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,实现了统计网站被访问次数的功能: ```java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; public class ShowTimesServlet extends HttpServlet { private int times = 0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); ServletContext context = this.getServletContext(); Integer count = (Integer)context.getAttribute("count"); if(count != null) { times = count; } times++; context.setAttribute("count", times); out.println("<html><head><title>统计网站被访问次数</title></head><body>"); out.println("<h2>网站被访问次数为:" + times + "</h2>"); out.println("</body></html>"); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 在该示例中,我们通过重写`doGet()`和`doPost()`方法来实现处理GET和POST请求。在`doGet()`方法中,我们首先获取`ServletContext`对象,然后获取之前保存的访问次数。如果之前有保存过访问次数,就将其赋值给`times`变量。然后将`times`加1,再将其保存到`ServletContext`对象中。最后输出网站被访问次数的信息。 在`doPost()`方法中,我们直接调用`doGet()`方法来处理请求。这是因为我们的目的是统计网站被访问次数,而不是处理POST请求。 需要注意的是,为了让`ServletContext`对象在多个请求之间共享数据,我们需要将它保存在服务器端而不是客户端。在这里,我们将访问次数保存在`ServletContext`对象中,以便在多个请求之间共享
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值