Servlet初始化 可以传入一些参数 通过 <init-param>来配置
新建 servletinit项目
新建包 com.xiaoan.test->new Class(TestInit.java)
package com.xiaoan.test; import java.io.IOException;
import java.util.Enumeration; import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; public class TestInit implements Servlet{ @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
} @Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
} @Override
public void init(ServletConfig arg0) throws ServletException {
//通过参数名获取参数值
String username = arg0.getInitParameter("username");
System.out.println("username: " + username); //获得所有的参数名 String 对象的 Enumeration
Enumeration<String> paramName = arg0.getInitParameterNames();
while(paramName.hasMoreElements()){
String param = paramName.nextElement();
String paramvalue = arg0.getInitParameter(param);
System.out.println(param + ": " + paramvalue);
} //获得servletname 了解
String servletname = arg0.getServletName();
System.out.println("servletName: " + servletname);
} @Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub } }
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>servletinit</display-name> <servlet>
<servlet-name>si</servlet-name>
<servlet-class>com.xiaoan.test.TestInit</servlet-class> <init-param>
<param-name>username</param-name>
<param-value>xiaoan</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param> <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>si</servlet-name>
<url-pattern>/si</url-pattern>
</servlet-mapping>
</web-app>
@Override
public void init(ServletConfig arg0) throws ServletException {
}
参数中ServletConfig: 封装了Servlet的配置信息, 并可以获取到ServletContext对象
1>配置Servlet的初始化参数
在<servlet>里面配置Servlet的初始化参数,并且必须放到load-on-startup的前面
<init-param>
<param-name>key</param-name>
<param-value>val</param-value>
</init-param>
按照以上格式可以配置多个初始化参数
2>获取初始化参数
获取初始化参数值
getInitParameter(String name)
以 String 对象的 Enumeration 的形式返回 servlet 的初始化参数的名称
getInitParameterNames()
返回此 servlet 实例的名称
getServletName()