5.3. Create and use context and init parameters
- Application init parameters
The class that the container will use at application level is ServletContext.
Defining init parameters in deployment descriptor:
Defining init parameters in deployment descriptor:
<context-param> <param-name>name1</param-name> <param-value>value1</param-value> </context-param>
Retrieving init parameters:
getServletContext().getInitParameter("parameter1");
For the initialization process in an application the ServletContextListener can be defined (this code will run before the rest of the application for example to get the init parameters and create a database connection,..etc).
For the initialization process in an application the ServletContextListener can be defined (this code will run before the rest of the application for example to get the init parameters and create a database connection,..etc).
<context-param> <param-name>name1</param-name> <param-value>value1</param-value> </context-param> <listener> <listener-class>example.MyServletContextListener</listener-class> </listener>
Example: The servletContextListener class will retrieve the init parameters, in this case a property "blogName", and then servletContext will be accessed to display the property.
This can be useful when we define properties as user, password, urls, driver and we want to create a database connection (at application level), and it will be perform before any servlet is initialized. It can be useful to access to properties file or other resources (IO operations) to retrieve global parameters.
- Servlet init parameters
ServletConfig methods:
-Parameters: getInitParameter(String name), getInitParameterNames()
-Context : getServletContext()
To use init parameters there are 2 options:
- By deployment descriptor
- By annotations
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>example.MyServlet</servlet-class>
<init-param>
<param-name>parameter1</param-name>
<param-value>value1</param-value>
</init-param>
<init-param>
<param-name>parameter2</param-name>
<param-value>value2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
- a complete path: /name/MyName.do
- a directory: /name/*
- an extension: *.do
The way to retrieve the init parameter in the code is:
getServletConfig().getInitParameter("parameter1");
5.4. Use annotations to configure servlets
From the specification Servlets3.0 is possible to declare servlets by annotations (an alternative to deployment descriptor)
@WebServlet(name="MyServlet",
urlPatterns={"/MyServlet"},
initParams={@WebInitParam(name="parameter1", value="value1"),
@WebInitParam(name="parameter2", value="value2")})
public class MyServlet extends HttpServlet {
WebListener annotation:
@WebListener
public class MyServletContextListener implements ServletContextListener {
OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification
No comments:
Post a Comment