1,在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数。
当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以得到当前servlet的初始化参数信息。
代码:(为servlet配置初始化参数)
ServletDemo8 cn.yujian.ServletDemo8 name xxxx charset UTF-8 url jdbc:mysql://localhost:3306/test username root password root config /WEB-INF/...
Java代码:(通过ServletConfig对象来获取servlet的初始化参数)
//servletConfig对象的使用public class ServletDemo8 extends HttpServlet { // 2.4 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = this.getServletConfig(); Enumeration e = config.getInitParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = config.getInitParameter(name); System.out.println(name + "=" + value); } String url = config.getInitParameter("url"); String username = config.getInitParameter("username"); String password = config.getInitParameter("password"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}