servlet中ServletConfig的使用

转自:http://www.zzzj.com/html/20090117/69483.html

前言

  相对于ServletContext,ServletConfig是针对特定的Servlet的参数或属性。ServletConfig是表示单独的Servlet的配置和参数,只是适用于特定的Servlet。从一个servlet被实例化后,对任何客户端在任何时候访问有效,但仅对本servlet有效,一个servlet的ServletConfig对象不能被另一个servlet访问

1. 首先要设置初始化参数,如果只有一个特定的servlet要设定的参数(Servlet名字以及其它参数等),其它servlet不能共享,应该配置为ServletConfig参数,如一个读取附件的servlet要用到绝对目录,而别的servlet不会用到:

<web-app>
    <servlet>
        <servlet-name>GetAtt</servlet-name>
        <servlet-class>mail.GetAttServlet</servlet-class>
        <init-param>
            <param-name>absPath</param-name>
            <param-value>/usr/mail/ax/axman/Maildir/</param-value>
        </init-param>
    </servlet>
</web-app>

2. 其次要取得ServletConfig对象:

1). 从init()方法中得到:

public class Test extends HttpServlet {
    ServletConfig config;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.config = config;
    }
}

2). 从getServletConfig()方法中得到:

ServletConfig config=this.getServletConfig();
if(config.getInitParameter("absPath").eaquals("adsd"){
   .......
}

3). 也可直接调用getInitParameter()方法获得参数值

posted @ 2014-03-13 07:03  horizon~~~  阅读(397)  评论(0编辑  收藏  举报