ServletContext 一个项目只有一个ServletContext 在多个servlet中传递参数
在web.xml中写全局变量
1、获取上下文对象
package com.zhiyou.servlet.demo02;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
@WebServlet(urlPatterns="/EServlet")
public class EServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletContext 一个项目只有一个ServletContext 在多个servlet中传递参数
//三种方法选择其一
//1、获取上下文对象
ServletContext context = getServletConfig().getServletContext();
String roleName=context.getInitParameter("roleName");
//2、 获取上下文对象
ServletContext context=this.getServletContext();
String roleName=context.getInitParameter("roleName");
//3、获取上下文对象
HttpSession session=req.getSession();
ServletContext context=session.getServletContext();
String roleName=context.getInitParameter("roleName");
//保存参数到上下文,供其他servlet调用
context.setAttribute("EServlet-param", "测试测试");
System.out.println("EServlet:"+roleName);
}
}