Advertisement



< Prev
Next >



ServletContext Parameters



A Servlet may use an object of ServletContext to communicate with the Servlet Container and access the context initialization parameters, the MIME type of a file, dispatch requests etc. Remember, there is only object of ServletContext per application.

In this tutorial, we are going to understand how to use, set the context initialization parameters with an object of ServletContext and how to read them out. The context initialization parameters are common and accessible to all the servlets in an application and hence are also called the application parameters. The context initialization parameters are set in the deployment descriptor file, web.xml




Note:


ServletContext is an interface and it is a part of the Servlet API. The full path to import and access all the methods provided by ServletContext is javax.servlet.ServletContext. Let us see some of its important methods.




Some methods of ServletContext


Method Description
Object getAttribute(String str)

This method gets an individual context attributes.

Enumeration getAttributesNames()
This method gets all the named of context attributes.

void setAttribute(String name, Object value)
This method sets the context attributes.

void removeAttribute(String name)
This method sets the context attributes.

String getInitParameter(String str)
This method gets an individual context parameter.

Enumeration getInitParameterNames()
This method returns all the names of the context initialization parameters.

String getMimeType(String file)
This method returns the MIME type of the specified file.

RequestDispatcher getRequestDispatcher(String path)
This method returns a RequestDispatcher object for the resource located at the given path.






Creating a webpage which calls the Servlet


We are creating a webpage which asks the user to click a button named, Yes, let's read!, which when clicked, displays the context initialization parameters and their values mentioned in the deployment descriptor file(web.xml).

Webpage1.jsp
<html>

<head>
<title> ServletRequest Demo </title>
</head>


<body>
<b>Do you want to read Context Initialization parameters?</b>
<br/>
<br/>
<br/>

<form action = "MyServlet">
<input type = "submit" value = "Yes, let's read!" />
</form>

</body>
</html>





Using ServletContext to read context initialization parameters


Next, we are going to create a Servlet by extending the GenericServlet abstract class. GenericServlet class implements Servlet and ServletConfig interface, hence we can directly call the methods of ServletConfig within this newly created Servlet.




MyServlet1.java
import java.io.*;
import javax.servlet.*;
import java.util.*;


public class MyServlet1 extends GenericServlet
{

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{

//Getting a ServletContext object
ServletContext servCon = getServletContext();

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2> Using ServletContext object</h2> ");


//Reading one parameter 
out.println("<b>Reading only one parameter its value </b> <br/>");
out.println("The Website name is " + servCon.getInitParameter("Website"));
out.println("<br/>");
out.println("<br/>");


//Reading all the parameters
out.println("</b> Reading all the parameter and their values </b>  <br/>");
Enumeration enum1 =  servCon.getInitParameterNames();
while(enum1.hasMoreElements())
{
String paramName = (String)enum1.nextElement();
String paramValue = servCon.getInitParameter(paramName);
out.println("Parameter "+ paramName + " has a value " + paramValue);
out.println("<br/>");
}
}

}




Advertisement




Software requirements


To execute this Servlet program, besides installing Java, we also need to install a web server i.e. a software required to run Servlet programs. There are number of web servers available in the market and we will install the Servlet standard - Apache Tomcat Server. For more, please read, How to install Apache Tomcat web server.




Directory Structure of Servlet files


Let us show you through a diagram on how to structure the files for the proper execution of this program.








Creating the Deployment Descriptor file


As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml. So, let's create one -


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Welcome tomcat</display-name>
  <description>
     Welcome tomcat
  </description>

<servlet>
 	<servlet-name>ServletContextExample</servlet-name>
	<servlet-class>MyServlet1</servlet-class>
</servlet>


<context-param>
	<param-name>Website</param-name>
	<param-value>Decodejava.com</param-value>
</context-param>

<context-param>
	<param-name>Message</param-name>
	<param-value>Never Give Up!</param-value>
</context-param>


<servlet-mapping>
	<servlet-name>ServletContextExample</servlet-name>
	<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

</web-app>


In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :



We have also specified two context initialization parameters common to all servlets using <context-param> tag. This tag has two child tags <param-name> and <param-value> :






Note:







Setting the classpath


Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java. Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named servlet-api.jar.

This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of Tomcat installation folder.

For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib

There are two ways to set the classpath -




Compiling the Servlet class


After setting the classpath, you need to compile the Servlet class by entering the command at the folder where you've stored the Servlet class file.

javac -d WEB-INF/classes MyServlet1.java





Executing the Servlet


To execute our Servlet, we first need to execute the webpage containing the form, which asks the user to enter the name and press the submit button.



As soon as the user enters the name and submits the form, the request goes to the Servlet.

Hence, you will see the URL containing the full path to the file with the request parameter -




When executed, this Servlet displays all the context initialization parameters using the methods of ServletContext object. Please remember - These context initialization parameters are associated with the whole application and are common to all its servlets.




Servlet Initialization Parameters vs Context Initialization Parameters







Please share this article -




< Prev
Next >
< Servlet Initialization Parameters
Servlet Context Attributes >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement