Servlet知識總結(5)——ServletContext
阿新 • • 發佈:2020-08-07
5.ServletContext
web容器啟動時,會為每個web程式建立一個對應的ServletContext物件,代表了當前的web應用,即在一個web應用中ServletContext是共有的(唯一)
1.共享資料
在一個Servlet中儲存的資料能在另一個Servlet中獲取到
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // this.getServletContext() servlet上下文 // this.getInitParameterNames() 初始化引數 // this.getServletConfig() servlet配置 ServletContext context = this.getServletContext(); String userName = "meeseek"; context.setAttribute("name",userName); System.out.println(" hello"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解決中文亂碼問題 resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); ServletContext servletContext = this.getServletContext(); String username = (String) servletContext.getAttribute("name"); resp.getWriter().print("名字為" + username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.shida.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.shida.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping>
測試訪問結果即可
2.獲取初始化引數
<!-- 配置一些web初始引數-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
<servlet>
<servlet-name>sd3</servlet-name>
<servlet-class>com.shida.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd3</servlet-name>
<url-pattern>/sd3</url-pattern>
</servlet-mapping>
啟動測試結果: