1.ServletContext在整个web应用程序生命周期内存在,用来保存全局对象,整个web应用都可以使用其获取context参数。当启动服务器后,servlet容器将读取web.xml中配置的context参数,进行初始化工作。ServletContext可以获取该参数。比如我们可以配置编码信息供web程序使用。
web.xml
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><web-app> <context-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </context-param> </web-app>
ReadEncoding.java读取context参数中的编码信息。

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->public class ReadEncoding extends HttpServlet { //获取servletcontext对象 ServletContext sc = this.ServletConfig.getServletContext(); //获取初始化参数 String encoding = sc.getInitParameter("encoding"); //设置响应的编码格式 response.setCharacterEncoding(encoding); }
为了方便获取ServletContext对象,servlet提供了一种简化的写法,this.getServletContext();
其实该方法内部也是调用了this.getServletConfig.getSerlvetContext。
2.ServletConfig对象保存着servlet的配置信息,当servlet被实例化后,web容器读取初始化参数,保存到config对象中,
每一个servlet都有一个servletconfig对象保存着自己的参数信息。
web.xml


<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><web-app> <servlet-name>myServlet</servlet-name> <servlet-class>com.cnblogs.7days.helloServlet</servlet-class> <intit-param> <param-name>blogname</param-name> <param-value>cnblogs</param-value> </intit-param> </web-app>
ReadBlogName.java
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->public class ReadBlogName extends HttpServlet { //读取配置的blogname String blogName = this.getServletConfig.getInitParameter("blogName"); System.out.println(blogName); }
同ServletContext一样,servlet容器也提供了一个简化获取servletconfig参数的方法,this.getInitParameter("blogName")。