由于在servlet创建时没有构造函数,当我们需要参数时可以使用初始化参数来初始化一些参数
在web.xml中添加<init-param>
<param-name>param1</param-name>
<param-value>param1</param-value>
</init-param>但是这些参数的作用域仅限于这个sevlet 不可以在多个servlet间共享
我们有两种方法获取servlet初始化参数
1 使用servlet的getInitParameter(String )方法 如果有,则返回他的值 没有返回null
2 使用servletConfig对象的getInitParameter(String )方法 返回值同上
<servlet> <servlet-name>FristServlet</servlet-name> <servlet-class>qdm.test.FirstServlet</servlet-class> <init-param> <param-name>param1</param-name> <param-value>param1</param-value> </init-param> <init-param> <param-name>param2</param-name> <param-value>param2</param-value> </init-param> <init-param> <param-name>param3</param-name> <param-value>param3</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>FristServlet</servlet-name> <url-pattern>/servlet/FirstServlet</url-pattern> </servlet-mapping>
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("第一种方法获取servlet初始化参数"); String param1=getInitParameter("param1"); String param2=getInitParameter("param2"); String param3=getInitParameter("param3"); System.out.println("param1"+param1); System.out.println("param2"+param2); System.out.println("param3"+param3); System.out.println("第二种方法获取servlet初始化参数"); ServletConfig config=getServletConfig(); String p1=config.getInitParameter("param1"); String p2=config.getInitParameter("param2"); String p3=config.getInitParameter("param3"); System.out.println("param1"+p1); System.out.println("param2"+p2); System.out.println("param3"+p3); }
运行结果如下
如果想在多个servlet间共享一些参数 则需要在上下文(context)设置初始化参数
<context-param> <param-name>context-name1</param-name> <param-value>context-value1</param-value></context-param>我们可以通过getServletConfig().getServletContext()来获取Context对象然后通过调用getInitParameter(String )来获取指定的参数 getIniteParameterNames()来获取全部参数名称
<context-param> <param-name>context-name1</param-name> <param-value>context-value1</param-value> </context-param> <context-param> <param-name>context-name2</param-name> <param-value>context-value2</param-value>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("获取context参数"); ServletContext context=getServletContext(); System.out.println("获取全部参数"); Enumeration names=context.getInitParameterNames(); while(names.hasMoreElements()) { String paraname=(String)names.nextElement(); String paravalue=context.getInitParameter(paraname); System.out.println("参数名:"+paraname+"-----值:"+paravalue); } }
运行效果如图
时间: 2024-10-13 16:20:14