ServletConfig学习
1.ServletConfig是什么?
获得servlet相关配置的对象(获取xml里面的内容)
2.ServletConfig对象
在xml(servlet)配置:
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>//通过:username索引,得到value 值:root
//可以在创建ServletConfig对象,中获得索引,进而获得value值
//ServletConfig config=this.getServletConfig();//创建对象ServletConfig
// String username=config.getInitParameter("username");//得到配置里面的值
<?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>
<servlet-name>demo2</servlet-name>
<servlet-class>com.example.demo16.HelloServlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>demo2</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>demo3</servlet-name>
<servlet-class>com.example.demo16.HelloSerrvlet3</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>abc</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>demo3</servlet-name>
<url-pattern>/helloo</url-pattern>
</servlet-mapping>
</web-app>
创建类
HelloSerrvlet3 extends HttpServlet :
使用doget方法:
里面再使用
ServletConfig config=this.getServletConfig();//创建ServletConfig对象
String username=config.getInitParameter(“username”);//得到配置里面的值
使用了:ServletConfig的API:getInitParameter();
获得配置里面的值
package com.example.demo16;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloSerrvlet3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
resp.getWriter().println("helloWolrd!");
ServletConfig config=this.getServletConfig();//创建对象ServletConfig
String username=config.getInitParameter("username");//得到配置里面的值
String password=config.getInitParameter("password");//也得到了
System.out.println(username+" "+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
效果:
每访问一次,就执行一次doget方法
root abc
获得所有参数:
Enumeration
Enumeration<String> names=config.getInitParameterNames();//获得所有参数值
while (names.hasMoreElements()){//遍历
String name=names.nextElement();//获取:name值
String value=config.getInitParameter(name);//获取name对于的value值
System.out.println(name+" "+value);
}
获取:名称
String servletName=config.getServletName();//获类取名称
System.out.println(servletName);//获取了xml这里面 <servlet-name>demo3</servlet-name>的名称