1 传值:web.xml传递参数 2 3 在web.xml中的Servlet里配置多个init-param 4 <servlet> 5 ... 6 <init-param> 7 <param-name>name</param-name> 8 <param-value>关羽</param-value> 9 </init-param> 10 <init-param> 11 <param-name>age</param-name> 12 <param-value>20</param-value> 13 </init-param> 14 <init-param> 15 <param-name>sex</param-name> 16 <param-value>男</param-value> 17 </init-param> 18 </servlet> 19 20 在servlet的init()方法中: 21 String name=this.getServletConfig().getInitParameter("name"); 22 String age=this.getServletConfig().getInitParameter("age"); 23 24 25 ServletConfig sc=this.getServletConfig();
//枚举 获取所有配置参数信息 26 Enumeration e=sc.getServletConfig().getInitParameterNames(); 27 while(e.hasMoreElements()){ 28 syso(sc.getInitParameter(e.nextElement().toString())); 29 } 30 31 32 ----------------------------------- 33 在web.xml中的web-app下配置多个context-param 34 <context-param> 35 <param-name></param-name> 36 <param-value></param-value> 37 </context-param> 38 39 <context-param> 40 <param-name></param-name> 41 <param-value></param-value> 42 </context-param> 43 44 45 context:一般指上下文环境 46 47 ServletContext:指的是整个web项目的上下文环境 ,表示的就是整个web.xml 48 49 this.getServletContext().getInitParameter("age"); 50 //可以通过局部获得整体(由子到父) 51 this.getServletConfig().getServletContext().getInitParameter("age"); 52 53 ServletConfig,ServletContext 可以直接从this(Servlet)中获得这两个对象
54 ServletConfig scf=this.getServletConfig(); 55 ServletContext sct=this.getServletContext(); 56 57 init(),init(ServletConfig config):在GenericServlet中,init(ServletConfig config) 里面调用init(),所以覆盖的是init(),而不是init(ServletConfig config)