Parse web.xml to get the parameters in context param and init param in the Servlet
- 2020-04-01 02:04:55
- OfStack
Two parameters can be defined in web.xml:
1. Parameters within the application scope, stored in the servletcontext, are configured in web.xml as follows:
2. Servlet-scoped parameters, which can only be obtained in the init() method of the servlet, are configured as follows in web.xml:
In the servlet, the code can be used separately:
The first parameter can be obtained from getServletContext(). GetInitParameter ("context/param") in the servlet
The second parameter can only be fetched in the init() method of the servlet through this.getinitparameter ("param1")
1. Parameters within the application scope, stored in the servletcontext, are configured in web.xml as follows:
<context-param>
<param-name>context/param</param-name>
<param-value>avalible during application</param-value>
</context-param>
2. Servlet-scoped parameters, which can only be obtained in the init() method of the servlet, are configured as follows in web.xml:
<servlet>
<servlet-name>MainServlet</servlet-name>
<servlet-class>com.wes.controller.MainServlet</servlet-class>
<init-param>
<param-name>param1</param-name>
<param-value>avalible in servlet init()</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
In the servlet, the code can be used separately:
package com.qisentech.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class MainServlet extends HttpServlet {
public MainServlet() {
super();
}
public void init() throws ServletException {
System.out.println(this.getInitParameter("param1"));
System.out.println(getServletContext().getInitParameter("context/param"));
}
}
The first parameter can be obtained from getServletContext(). GetInitParameter ("context/param") in the servlet
The second parameter can only be fetched in the init() method of the servlet through this.getinitparameter ("param1")