一:ServletConfig对象
1:用来封装数据初始化参数,在服务器web.xml配置文件中可以使用<init-param>标签配置初始化参数。
2:实例演示
web.xml文件中配置初始化参数:
1 <servlet> 2 <servlet-name>ServletDemo</servlet-name> 3 <servlet-class>com.hlcui.servlet.ServletDemo</servlet-class> 4 <init-param> 5 <param-name>name</param-name> 6 <param-value>Tom</param-value> 7 </init-param> 8 <init-param> 9 <param-name>age</param-name> 10 <param-value>26</param-value> 11 </init-param> 12 <init-param> 13 <param-name>salary</param-name> 14 <param-value>12000</param-value> 15 </init-param> 16 </servlet>
servlet类中读入参数:
1 public void doGet(HttpServletRequest request, HttpServletResponse response) { 2 // 根据参数名,获取指定属性值 3 String value = this.getServletConfig().getInitParameter("name"); 4 System.out.println("value=" + value); 5 System.out.println(".........."); 6 // 获取多个属性值 7 Enumeration e = this.getServletConfig().getInitParameterNames(); 8 while (e.hasMoreElements()) { 9 String name = (String) e.nextElement(); 10 String value2 = this.getServletConfig().getInitParameter(name); 11 System.out.println(name + "=" + value2); 12 } 13 }
在web.xml中配置初始化参数,然后在创建servlet实例时调用init()方法将servletconfig对象传给servlet类。
1 private ServletConfig config; 2 3 public void doGet(HttpServletRequest request, HttpServletResponse response) { 4 String value = config.getInitParameter("name"); 5 System.out.println(value); 6 } 7 8 public void init(ServletConfig config) { 9 this.config = config; 10 }
只是httpServlet的实现类GenericServlet已经帮我们做好了这些工作。
二:ServletContext对象
时间: 2024-10-01 20:51:36