1、首先在web.xml中定义两个初始化变量
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置servlet让tomcat加载-->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.gxa.servlet.HelloServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>博客</param-value>
</init-param>
<init-param>
<param-name>age</param-name>
<param-value>14</param-value>
</init-param>
</servlet>
<!--映射路径(虚拟路径)-->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<!--配置虚拟路径-->
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
</web-app>
2、在servlet中的service方法里获取初始化参数
package com.gxa.servlet;
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
public class HelloServlet implements Servlet {
private ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("hello servlet");
//获取初始化参数----第一种方式
String name = servletConfig.getInitParameter("name");
String age = servletConfig.getInitParameter("age");
System.out.println("name:" + name + "-age:" + age);
//获取初始化参数----第二种方式
Enumeration<String> names = servletConfig.getInitParameterNames();
if (names.hasMoreElements()) {
String key = names.nextElement();
System.out.println("key:" + servletConfig.getInitParameter(key));
}
response.getWriter().write("hello servlet binggo");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}