[servlet面试题]在servlet中的init中使用getInitParameter出现空指针错误

更新时间:2017-08-19    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

 
原因:
创建servlet时勾中了需要实现的方法中init(ServletConfig config)带有config参数,此时用this. getInitParameter方法会失效,不能从web.xml中读取初始化参数,具体应该用什么方法得到初始参数没有研究。
 
解决方法:

实现init()不带参数的方法,使用this. getInitParameter方法就会成功。


网站关于init用法


init方法,从源码中我们不难发现:Servlet接口里面只有init(ServletConfig),这是供tomcat调用的。GenericServlet类里面有成员变量ServletConfig,init(ServletConfig)方法和init()方法:

                

 代码如下

        private transient ServletConfig config;

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

                        public void init() throws ServletException{

                        }


现在一切都很明了了,当容器(tomcat)帮忙调用init(ServletConfig config)并且给传过来一个参数config,这个方法把参数对象的引用指向类的成员变量this.config,并且调用类的 this.init()方法。如果我们在写Servlet类时只要重写init(ServletConfig config)就可以了

本文来源:http://www.bbyears.com/wangyezhizuo/34951.html

热门标签

更多>>

本类排行