用ServletContext简单实现共享数据
发布日期:2022-03-09 00:49:18 浏览次数:43 分类:技术文章

本文共 1198 字,大约阅读时间需要 3 分钟。

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的映射

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

转载地址:https://blog.csdn.net/m0_57831732/article/details/122260666 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Integer<-->String
下一篇:Mybatis中 模糊查询的两种方式

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年03月27日 18时44分27秒