java-web servletContext共享数据

servletContext共享数据

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

 

1.在某个servlet中保存数据

package com.changfan.servlet1;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
     //存放变量
        context.setAttribute("userName","changfan");
    }

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

 

2.在另一个servlet中读取数据

package com.changfan.servlet1;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Getc extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();

        String userName = (String) context.getAttribute("userName");
        PrintWriter writer = resp.getWriter();
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        writer.println("用户名:"+userName);
    }

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

 

 

 

 

 

posted @ 2023-03-13 00:11  changfan  阅读(20)  评论(0编辑  收藏  举报