一段java代码,我不是很理解,希望大家帮我看下解释下,很是感谢,急

1:
public void init() throws ServletException
{
ServletContext cnt = this.getServletContext();
ContextObject obj = new ContextObject();
obj.starTimeStamp();
cnt.setAttribute("obj",obj);
}
-------------------------------------------------------
2:
public void init(ServletConfig cnf) throws ServletException
{
super.init(cnf);
ServletContext cnt = cnf.getServletContext();
ContextObject obj = new ContextObject();
obj.starTimeStamp();
cnt.setAttribute("obj",obj);
}

这两个的区别是什么,也就是说,我糊涂了,请教!!!
看下我的理解,这是第一个里面的
ServletContext cnt = this.getServletContext(); //这个是得到当前上下文。??
ContextObject obj = new ContextObject(); //这是实例化另一个类。??
obj.starTimeStamp(); // 这里是调用那个累的一个方法,不是这里有疑问
cnt.setAttribute("obj",obj); //这是往ServletContext添加obj对象。
但是就是第二个里的 init(ServletConfig cnf)这个是又参数的init,
super.init(cnf);是这里我不明白的,就是init里有参数,不用super为什么不行,哎 有点乱,还是求大家帮我看看,最好详细的说下这几个的工作方式,我谢谢大家了

就是那个上下文这个词语在这里不是很懂,getServletContext()//获得上下文 这个ServletContext是什么,是个作用域?可以说是内存变量吗?作用是什么,我好乱

这个是一个配置的servlet
<servlet>
<servlet-name>ipLogServlet</servlet-name>
<servlet-class>com.allanlxf.servlet.life.IpLogServlet</servlet-class>
<init-param>
<param-name>file1</param-name>
<param-value>c:/iplog.txt</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

下面是这个serlvet的init方法
public void init(ServletConfig config) throws ServletException
{
super.init(config);
String file = config.getInitParameter("file");
if(file == null)
{
System.out.println("lack of config parameter named file");
throw new ServletException("lack of config parameter named file");
}

try
{
logger = new PrintWriter(new FileOutputStream(file, true));
}catch(Exception e)
{
throw new ServletException("can not find file " + file);
}
}

一般,如果我们在xml配置了 <init-param></init-param>,我们一般会用int(ServletConfig config),否则,我们只用 int()无参的函数就可以了
至于 int(ServletConfig config) 要加这句super.init(cnf); ,是为了让父类通过config来读取放进ServletContext(上下文)中!如果你不写int(config),那么就要自己写 config.getServletContext()...我忘记怎么写了,好久没有用过serlvet了,有点麻烦而已!
ServletContext 里面包含了一个应用的所有东西,就像一个数据库一样,只是数据库存在磁盘上,而servletContext存在一个虚拟的地方,一旦应用结束,serveltContext就不存在了!ServletContext里面包含整个应用的参数等信息
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-03-07
不知道,我看了也有一点头晕,高手请给个答案,谢谢!
第2个回答  2008-03-07
当子类继承父类后,要是子类中直接调用父类的构造方法,就写super。明白了吗
第3个回答  2008-03-07
最好把完全的代码贴上来,看代码不要把英文翻译成中文,那只能会更乱乎