Servlet为什么有两个init方法


package com.bjsxt;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestInitServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=GBK");     
		PrintWriter out = resp.getWriter();
		
		out.println(this.getServletConfig().getServletName());

		java.util.Enumeration params = this.getServletConfig()
				.getInitParameterNames();   
		for (; params.hasMoreElements();) {
			String name = params.nextElement().toString();
			String value = this.getServletConfig().getInitParameter(name);
			out.println(value);
		}
		out.close();  
	}

}



  <servlet>
    <servlet-name>TestInitServlet</servlet-name>
    <servlet-class>com.bjsxt.TestInitServlet</servlet-class>
	    <init-param>
			<param-name>name</param-name>
			<param-value>小王</param-value>
	    </init-param>
		<init-param>
			<param-name>gender</param-name>
			<param-value>男</param-value>
		</init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestInitServlet</servlet-name>
    <url-pattern>/servlet/TestInitServlet</url-pattern>
  </servlet-mapping>
  输出:TestInitServlet 小王 男

有些朋友会发现在GenericServlet为什么要有两个init方法呢?
public void init()
  A convenience method which can be overridden so that there's no need to call super.init(config).

void init(ServletConfig config)
  Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
如果不提供init()方法的话,我们如果重写init(config)又忘记写super.init(config)了的话,就会出错
实际上就是怕程序员忘记写super.init(config)
现在提供了init()方法了它说so that there's no need to call super.init(config).

你可能感兴趣的:(servlet)