Servlet context是外部应用程序的全局对象,用于存储在整个应用程序中需要持久保存的数据。它随着应用程序的启动而创建,并在应用程序重启或关闭时销毁。通过servlet context,可以方便地实现全局数据的共享和持久化,如网站的备案信息等。
package com.imooc.servlet.servletcontext;
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("/servletcontext/init")
public class ServletContextInitServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("copyright", "Copyright© 2021 imooc.com 京ICP备 12003892号-11 京公网安备11010802030151号");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("ServletContext已初始化");
}
}
package com.imooc.servlet.servletcontext;
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;
import java.io.PrintWriter;
@WebServlet("/servletcontext/index")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
ServletContext context = request.getServletContext();
String copyright = (String) context.getAttribute("copyright");
PrintWriter out = response.getWriter();
out.println("导航栏");
out.println("<hr/>");
out.println("首页正文");
out.println("<hr/>");
out.println(copyright);
}
}