---
title: "ServletConfig与ServletContext的关系及使用"
author: "topfeng"
date: "2010-12-19T12:34:31Z"
tags: []
categories: ["企业架构"]
slug: "servletconfig-servletcontext"
draft: false
lastmod: "2010-12-19T12:37:33Z"
id: 846577
url: "https://topfeng.iteye.com/blog/846577"
---

ServletConfig:从一个Servlet被实例化后，对任何客户端在任何时候访问有效，但仅对本Servlet有效（即不是针对所有的Servlet），一个servlet的ServletConfig对象不能被另一个servlet访问。

的配置，为了不使用“硬编码”，应该配置为ServletContext参数，比如字符集的设定。  
  ServletContext:对任何servlet，任何客户端在任何时间都有效（对整个应用而言），这才是真正全局的对象。

  那么，ServletConfig参数和ServletContext参数到底应该如何使用，如何取得？  
  一般来说，对整个应用的配置，为了不使用“硬编码”，应该配置为ServletContext参数，比如字符集的设定。

  而如果只有一个特定的servlet要设定的参数，其它servlet不能共享，应该配置为ServletConfig参数，比如获得这个Servlet的作者。

  访问ServletConfig参数：  
  首先要取得ServletConfig对象，然后调用它的getInitParameter();方法。要访问  
ServletConfig对象，jsp中直接使用config内置对象，但因为你的JSP编译后的servlet一般不会被加到web.xml中的，所以一般不会通过jsp来取对本JSP编译后的servlet的配置参数，那么在servlet中要得到ServletConfig对象一般的方法：  
  在init()方法中取到：通过init的重载方法传递 ：  
public class Test extends HttpServlet{  
  ServletConfig config;  
  public void init(ServletConfig config) throws ServletException {  
  this.config = config;  
}  
  然后在下面的方法中就可以访问config对象。但要注意，为了确保能从构造方法中到到当前servlet的config对象，应该调用父类的构造方法：

public class Test extends HttpServlet  
{  
  ServletConfig config;  
  public void init(ServletConfig config) throws ServletException {  
  super.init(config);  
  this.config = config;  
}   
  通过getServletConfig()方法直接到时，这样做的好处是不必调手工传递属性，想在任何时候都可以得到。  
  要访问ServletContext对象，只要从现有的ServletConfig对象中servletContext=getServletContext()就可以了，然后调用servletContext.getInitParameter()方法就可以获取它的参数。