String
Enumeration
ServletContext
获取ServletContext [Servlet上下文] 对象。
String
获取servletname
先上代码:
AServlet.java
packagecom.zhixi.zhang;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.Enumeration;importjavax.servlet.Servlet;importjavax.servlet.ServletConfig;importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;public class AServlet implementsServlet {privateServletConfig config;
@Overridepublic void init(ServletConfig config) throwsServletException {//将局部变里config赋值给实例变里config//目的:在service方法中也可以使用config
this.config =config;
System.out.println("AServlet --> ServletConfig = "+config.toString());
}
@Overridepublic void service(ServletRequest request, ServletResponse response) throwsServletException, IOException {//将value打印到网页
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();//获取ServletConfig对象
ServletConfig config =getServletConfig();/*//通过初始化参数的name获取value
String driver = config.getInitParameter("driver");
String url = config.getInitParameter("url");
String user = config.getInitParameter("user");
String password = config.getInitParameter("password");
//获取所有出初始化参数的名字
Enumeration initParameterNames = config.getInitParameterNames();
//遍历输出
while(initParameterNames.hasMoreElements()){
String name = initParameterNames.nextElement();
//通过name获取value
String value = config.getInitParameter(name);
out.print(name+"="+value);
out.print("
");
}
out.print("
");
out.print(driver);
out.print("
");
out.print(url);
out.print("
");
out.print(user);
out.print("
");
out.print(password);*/
//获取servletname
String servletName =config.getServletName();
out.print(""+servletName+"");
out.print("
");//打印getSerrvletContext
ServletContext servletContext =config.getServletContext();
out.print(servletContext);//org.apache.catalina.core.ApplicationContextFacade@16d12dde
}
@Overridepublic voiddestroy() {
}
@OverridepublicServletConfig getServletConfig() {returnconfig;
}publicString getServletInfo() {return null;
}
}
View Code
web.xml
老杜Servlet_04_ServletConfig接口
index.html
a
com.zhixi.zhang.AServlet
driver
com.mysql.jdbc.Driver
url
jdbc:mysql//localhost:3306/bjpowernode
user
root
password
adamin123
a
/a
b
com.zhixi.zhang.BServlet
b
/b
View Code
方法分析:
1 getInitParmeter(String name)
//web.xml信息
//java文件
//获取到对应的value信息
2 getInitParameterNames():
//输出
3 getServletContext():
4 getServletName()
获取servletname
ServletConfig到底是什么?
ServletConfig是一个Servlet对象的配置信息对象,ServletConfig对象中封装了一个Servlet对象的置信息。Servlet对象的配置信息到web.xml文件中。
一个Servlet对象对应一个ServletConfig对象,100个Servlet对象对应100个ServletConfig对象。