Programmingempire
This article explains Registering a Servlet in Deployment Descriptor. Basically, registering a servlet in the deployment descriptor requires providing the <servlet> tag in the web.xml file. Also, within this tag, the <servlet-name>, and <servlet-class> tags specify the name of servlet and associated java class respectively.
Additionally, we can also specify <init-parameter> tags to provide the initialization parameters for a servlet. The following example demonstrates registering a servlet.
Creating a Servlet
At first, we create a servlet called WelcomeServlet containing the doGet() method. The following code shows how to display the Welcome message using a servlet.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter ob=response.getWriter();
ob.println("<html><body>");
ob.println("<center><h2>Welcome to Servlet Programming!!!");
ob.println("</h2></center>");
}
}
The following figure shows the output.
Output
Registering a Servlet
Now that, we have created our servlet, we can register it in the web.xml. In order to create web.xml, follow the steps given in this article. For the purpose of registering the servlet, we specify the corresponding tags. The following code shows how to register servlet in web.xml.
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
Further, we specify the <servlet-mapping> tag for prividing URL pattern. The following code shows how to specify URL pattern.
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/mywelcomeservlet</url-pattern>
</servlet-mapping>
As a result of specifying the URL pattern, the following output is produced.
Output
As can be seen in the output, the URL pattern we have specified in the web.xml is shown in the address bar, when we run this servlet. Apart from specifying the URL pattern, we can also privide the initialization parameters using the <init-param> tag. Bascally, the initialization parameters are specific to a particular servlet. Hence, these parameters are available in that servlet only. Also, we can access the init parameters in a servlet using a ServletConfig object. In fact, the Web container creates a ServletConfig object for each servlet in the web application. In other words, a separate ServletConfig object is created for each servlet.
Also, you can find an example on using initialization parameters here.