标签:abc 加载 public info 获得 context https alt tco
每一个Web工程对应于一个ServletContext对象,此对象代表web应用。
1、生命周期:
创建:web应用被加载到服务器或服务器开启。
销毁:web应用被移除或服务器关闭。
2、对象的获取:
(1)实现Servlet接口的类内部:
public void init(ServletConfig servletConfig) throws ServletException { ServletContext servletContext= servletConfig.getServletContext(); }
(2)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext=getServletContext(); }
3、ServletContext对象的应用:
(1)获得初始化参数:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
<context-param>
<param-name>zhai</param-name>
<param-value>zhai1997</param-value>
</context-param>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext=getServletContext(); String paramvalue=servletContext.getInitParameter("zhai"); System.out.println(paramvalue); }

(2)获得工程发布后的绝对路径:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext=getServletContext(); String realpath=servletContext.getRealPath("/web.text"); System.out.println(realpath); String realpath1=servletContext.getRealPath("/WEB-INF/wen-inf.text"); System.out.println(realpath1); String realpath2=servletContext.getRealPath("../工程.text"); System.out.println(realpath2); }


getRealPath的参数为相对于web的路径,因为发布到服务器的时候只发布web文件中的内容,因此:工程.text文件不能被访问到。
标签:abc 加载 public info 获得 context https alt tco
原文地址:https://www.cnblogs.com/zhai1997/p/11481736.html