一、介绍
ServletContext对象能获取web项目信息,一个web项目只有一个ServletContext对象。ServletContext对象在Tomcat启动时创建。
二、项目测试
(1)继承HttpServlet类
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//获取web项目的上下文路径
String contextPath = servletContext.getContextPath();
System.out.println(contextPath);
//获取全局配置参数
Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
while (initParameterNames.hasMoreElements()){
String name = initParameterNames.nextElement();
String value = servletContext.getInitParameter(name);
System.out.println("name:" + name + ", value:" + value);
}
}
}
(2)编写web.xml文件,配置Servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>username</param-name>
<param-value>hello</param-value>
</context-param>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.wsh.servlet.MyServlet</servlet-class>
<!--load-on-startup的值大于等于0时,Servlet在Tomcat启动时初始化-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
(3)配置Tomcat中的项目上下文路径
(4)运行