01_5_SERVLET为什么有2个init方法

时间:2021-05-21 04:26:50

01_5_SERVLET为什么有2init方法

1. web.xml配置初始化参数

 <servlet>

    <servlet-name>TestInitServlet</servlet-name>

    <servlet-class>TestInitServlet</servlet-class>

    <init-param>

   <param-name>language</param-name>

    <param-value>中文</param-value>

    </init-param>

    <init-param>

   <param-name>work</param-name>

    <param-value>Java开发工程师</param-value>

    </init-param>

  </servlet>

2. servlet中获取遍历获取参数

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html; charset=utf-8");

PrintWriter out = response.getWriter();

System.out.println("English");

System.out.println("中文");

String servletName = null;

String language = null;

servletName = this.getServletConfig().getServletName();

language = this.getServletConfig().getInitParameter("language");

System.out.println(servletName);

out.print("<body>语言:Enlish<br/>语言:中文<br/>Servlet名称:");

out.println(servletName);

//利用枚举类循环取出初始化参数,并打印出来

Enumeration en = this.getServletConfig().getInitParameterNames();

for (; en.hasMoreElements();) {

String name = null, value = null;

//获取初始化参数名

name = en.nextElement().toString();

//获取参数名的内容

value = this.getServletConfig().getInitParameter(name);

//打印到后台的内容

System.out.print("参数名为:");

System.out.print(name);

System.out.print(" 参数值为:");

System.out.print(value);

System.out.println();

//打印到页面的内容

out.println("<br/>初始化参数名为:");

out.print(name);

out.println(" 初始化值为:");

out.println(value);

}

 

out.print("</body>");

out.close();

}

3. 测试

语言:Enlish
语言:中文
Servlet名称:TestInitServlet
初始化参数名为: work 初始化值为: Java开发工程师
初始化参数名为: language 初始化值为:中文

4. 备注

为防止this.getServletConfig()获取参数不为null,我们一般重写init()方法,不会重写init(ServletConifg config)方法