package web;import java.io.IOException;import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class SomeServlet  extends HttpServlet{

public SomeServlet() {
System.out.println("constructor...");
}


public void init(ServletConfig config) throws ServletException {
System.out.println("init...");
}
public void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {





System.out.println("service...");
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException{
System.out.println("doGet...");
//获得请求资源的地址
// String uri = 
// request.getRequestURI();
// String path = 
// uri.substring(uri.lastIndexOf("/"),
// uri.lastIndexOf("."));
// System.out.println("path:" + path);
// PrintWriter out = response.getWriter();
// if(path.equals("/del")){
// out.println("del....");
// }
// if(path.equals("/add")){
// out.println("add....");
// }
//
// out.close();
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException{
doGet(request,response);
}
public void destroy() {
System.out.println("destroy...");
}


}
看到网上说重写init(ServletConfig config)有参方法  要在方法中super.init(config)否则会空指针但我没有写   实际运行时并没有产生空指针异常
另外init如果写空参的方法   调用时是否就只调用空参的init(ServletConfig config)就不调用了如果init不覆写这个方法    实际运行中还是会调用init(ServletConfig config)方法吗?

解决方案 »

  1.   

    你调用一下config看看是否会出现空指针异常?
      

  2.   

    不太可能init的两个重载版本都会调用,你看一下用无参init方法“覆写”时,是不是真的覆盖了(eclipse可以帮助检测)
      

  3.   

    HttpServlet继承GenericServlet,GenericServlet提供了servlet的默认两个init方法的实现
    先看看GenericServlet源码的两init方法: public void init(ServletConfig config) throws ServletException {
        this.config = config;
         this.init();
            }
     public void init() throws ServletException { }而Servlet接口提供的初始化方法只有一个 public void init(ServletConfig config) (看源码),
    所以init(config)才是对servlet接口的实现,而init()只是为了给开发者扩展自己功能用的,默认的 init(config)调用init(),另外就是对config赋值。
    下面回答下问题:
    1、重写init(ServletConfig config),没有写super.init(config),在init(config)内部不会报错,但是由于没有设置config,所以当servlet对象调用getServletConfig()时返回null,接下来就会导致web.xml中配置的参数取不到了。
    2、init写空方法,初始化调用的仍然是init(ServletConfig config),init(config)内部调用init().
    3、一样。