获取servletContext对象的方式:
1.代码如下:
package eduask;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
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;
/**
* Servlet implementation class Demo7
*/
@WebServlet("/Demo7")
public class TestServletContext extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//获取servletcontext对象 方式一
// ServletContext context=this.getServletConfig().getServletContext();
//方式二
ServletContext context=this.getServletContext();
String str=this.getServletContext().getInitParameter("company");
System.out.println(str);
}
}
2.web.xml的配置文件,配置结果如下:
<servlet>
<servlet-name>myServletContext</servlet-name>
<servlet-class>eduask.TestServletContext</servlet-class>
</servlet>
<context-param>
<param-name>company</param-name>
<param-value>众汇云聚科技有限公司</param-value>
</context-param>
<servlet-mapping>
<servlet-name>myServletContext</servlet-name>
<url-pattern>/servletContext</url-pattern>
</servlet-mapping>
3.启动tomcat,在浏览器中输入:
http://localhost:8080/webDemo/servletContext
4.在控制台中会显示:众汇云聚科技有限公司