• 渚漪Day13——JavaWeb 04【ServletContext】


    2、ServletContext

    web容器在启动的时候,他会为每个web程序都创建一个对应的servletContext对象,他代表了当前的web应用

    1.共享数据

    • 在一个Servlet中保存的数据,可以再另外一个Servlet中拿到

    • 如图在打开ms之前姓名为空

    • 开启ms后刷新,

    • 示例代码:

    public class myServletContext extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            String username = "鹿乃";
            context.setAttribute("username", username);
        }
    
    }
    
    public class ServletReceiver extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            String name = (String) context.getAttribute("username");
    
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().println("姓名:"+name);
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    <servlet>
        <servlet-name>ms</servlet-name>
        <servlet-class>myServletContext</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ms</servlet-name>
        <url-pattern>/ms</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>ServletReceiver</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/sr</url-pattern>
    </servlet-mapping>
    

    2.获取初始数据

    context.getInitParameter("url");
    

    3. 请求转发

    context.getRequestDispatcher("/sr").forward(req, resp);
    

    4.读取资源文件

  • 相关阅读:
    uni-app、VUE、微信小程序之异同
    git学习之通俗易懂篇(四)
    css学习之-----flex布局
    git学习之通俗易懂篇(三)
    git学习之通俗易懂篇(二)
    防止非法登录
    MVC 路由配置
    C# 跨线程调用控件
    【推荐】gitee 的使用,sts4公钥私钥的配置,
    查看java的springboot的内存占用
  • 原文地址:https://www.cnblogs.com/ijuysama/p/12774202.html
Copyright © 2020-2023  润新知