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);