Detailed explanation of ServletConfig and ServletContext objects

Detailed explanation of ServletConfig and ServletContext objects

1. ServletConfig object
   In the servlet configuration file, you can use one or more <init-param> tags to configure some initialization parameters for the servlet. (Configured under a servlet tag or the entire web-app)

   After the servlet is configured with initialization parameters, the web container will automatically encapsulate these initialization parameters into the ServletConfig object when creating the servlet instance object, and pass the ServletConfig object to the servlet when calling the servlet's init method. Furthermore, the programmer can get the initialization parameter information of the current servlet through the ServletConfig object.

First, you need to create private variables: private ServletConfig config = null;

Second, to rewrite the init method, pass in config, let this.config = config; to get the ServletConfig object

Finally, you can get the configuration information in <init-parm>

//Get the initialization parameter
  String value1 =this.config.getInitParameter("x1");

//Get the value corresponding to the name under the <init-param> tag in the configuration document
  String vlaue2 =this.config.getInitParameter("x2");
  
  //2. Get all the initialization parameters (received with Enumeration)
  Enumeration e =this. config.getInitParameterNames();
  while(e.hasMoreElements()){
   String name =(String) e.nextElement();
   String value= this.config.getInitParameter(name);
   System.out.println(name+ "=" + value);
  }

   The role of ServletConfig in development is as follows:

1) Get the character set encoding

  String charset =this.config.getInitParameter("charset");
2) Get database connection information

  String url =this.config.getInitParameter("url");
  String username =this.config.getInitParameter("username");
  String password =this.config.getInitParameter("password");
3)获得配置文件

  String configFile =this.config.getInitParameter("config");


2. ServletContext object

 When the WEB container is started, it will create a corresponding ServletContext object for each WEB application, which represents the current web application.

 1) ServletContext object application 1: use it to achieve data sharing among multiple web components

 The reference of the ServletContext object is maintained in the ServletConfig object. When developers write servlets, they can obtain the ServletContext object through the ServletConfig.getServletContext method. Since all servlets in a WEB application share the same ServletContext object, communication between servlet objects can be achieved through the ServletContext object. The ServletContext object is also commonly referred to as the context domain object.

In serlvet, you can use the following statement to set up data sharing

  ServletContext context =this.getServletContext(); //servletContext domain object
  context.setAttribute("data","shared data"); //save a data attribute to the domain

In another servlet, you can use the following statement to get the data attribute in the domain

  ServletContext context =this.getServletContext();
  String value = (String)context.getAttribute("data"); //Get the data attribute in the domain
  System.out.println(value);

 2) Obtain the configuration information of the entire web application through the servletContext object

  String url =this.getServletContext().getInitParameter("url");

  String username =this.getServletContext().getInitParameter("username");
  String password =this.getServletContext().getInitParameter("password");

  3) Implement servlet forwarding through the servletContext object

Since the java data in the servlet is not easy to set the style, so serlvet can forward the java data to the JSP page for processing

 this.getServletContext().setAttribute("data","serlvet数据转发");
  RequestDispatcher rd =this.getServletContext().getRequestDispatcher("/viewdata.jsp");
  rd.forward(request,response);

 4) Read the resource file through the servletContext object

 In actual development, the file types used as resource files are usually: xml, properties, and reading the xml file must parse the xml document, so the following example only reads the properties file (in a web project, As long as it comes to writing addresses, it is recommended to start with /)

 In web projects, generally speaking, we cannot read the configuration file in the traditional way, because it is relative to the startup directory of JVM (bin directory of tomcat), so we need to use the web absolute directory to get the address of the configuration file

  Three ways to read resource files:

 The first: use the getResourceAsStream method of ServletContext: return the read byte stream of the resource file

  InputStream in =this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
  Properties prop = newProperties();  

  prop.load(in);
  String url =prop.getProperty("url");

 The second: use the getRealPath method of ServletContext to obtain the complete absolute path path of the file, and then use the byte stream to read the file under the path

  String path =this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
  String filename =path.substring(path.lastIndexOf("\\")+1); 

  //The advantage over the first method is: In addition to getting data, you can also get the name of the resource file
  FileInputStream in = newFileInputStream(path);
  Properties prop = newProperties();
  prop.load(in);
  String url =prop .getProperty("url");

 The third type: use the getResource method of ServletContext to obtain a url object, call the openStream method of this class to return a byte stream, and read the data

  URL url =this.getServletContext().getResource("/WEB-INF/classes/db.properties");
  InputStream in =url.openStream();
  Properties prop = newProperties();
  prop.load(in);
  String url1 =prop.getProperty("url");

  5) How to read resource files in different locations in a web project

  1. When the resource file is under the package
  InputStream in =this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/itcast/context/db.properties");
  System.out.println(in);
  
  2 , The resource file is in the web-inf
  in =this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
  System.out.println(in);
  
  3. The resource file is in the web project
  in =this .getServletContext().getResourceAsStream("/db.properties");
  System.out.println(in);

 6) How to read configuration files in non-servlet programs: use class loader

1) Read with class loading 

 in =StudentDao.class.getClassLoader().getResourceAsStream("cn/itcast/context/db.properties");
2) Use class loading to read and treat resources as urls

 URL url =StudentDao.class.getClassLoader().getResource("db.properties");

 This can get the resource file name: String path = url.getPath();

3) Note: During the sleep process of the thread, even if the resource file is changed, the original content is still obtained.

solution:

  URL url =StudentDao.class.getClassLoader().getResource("db.properties");
  String path =url.getPath();
  
  FileInputStream in = newFileInputStream(path);
  Properties prop = newProperties();
  prop.load(in);
  System.out.println(prop.getProperty("url"));
  
  try {
   Thread.sleep(1000*15);
  } catch (InterruptedExceptione) {
    e.printStackTrace();
  }
  in = newFileInputStream(path);
  prop = new Properties();
  prop.load(in);
  System.out.println(prop.getProperty("url"));

 

4) Note: When using the class loader to read the resource file, you must pay attention that the resource file must not be too large, otherwise it will easily lead to memory overflow

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326157876&siteId=291194637