欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet 上下文

程序员文章站 2022-05-24 14:36:57
...
package com.example.demo.learn.servlet.context;

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

/**
 * 上下文的作用域,保存在服务器端, 不建议使用。
 * 多用户共享,类似全局变量
 */
@WebServlet("/ServletContextDemo")
public class ServletContextDemo extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 重定向到另外一个servlet路径
        ServletContext servletContext = this.getServletContext();
        servletContext.setAttribute("name","song");
        servletContext.setAttribute("age",20);
    }
}
package com.example.demo.learn.servlet.context;

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

@WebServlet("/ServletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String name = (String) servletContext.getAttribute("name");
        Integer age = (Integer) servletContext.getAttribute("age");
        System.out.println(name + " >> " + age);
    }
}