How to use web.xml in Servlet 3.0

In this tutorial you will learn how to use web.xml in Servlet 3.0.

How to use web.xml in Servlet 3.0

In this tutorial you will learn how to use web.xml in Servlet 3.0.

How to use web.xml in Servlet 3.0

How to use web.xml in Servlet 3.0

In this tutorial you will learn how to use web.xml in Servlet 3.0.

Here I am giving the simple example of a Servlet in which I make a simple servlet class using @WebServlet annotaion into which the initial parameter is given using @WebInitParameter annotation. To find the context value I have mapped the <context-param> element in web.xml. Because there is no any annotation is defined for the ServletContext.

Example :

ContextParamServlet.java

package roseindia.webContext;

import java.io.PrintWriter;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;

@WebServlet(name = "ContextParamServlet",
urlPatterns = {"/ContextParamServlet"},
initParams={
@WebInitParam(name="URL", value="jdbc:mysql://192.168.10.13"),
@WebInitParam(name="USER", value="root"),
@WebInitParam(name="PASSWORD", value="root")
} 
)
public class ContextParamServlet extends HttpServlet 
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException 
{

res.setContentType("text/plain");
PrintWriter out = res.getWriter();

String url = getInitParameter("URL");

ServletConfig config = getServletConfig();
ServletContext context = getServletContext();

String uid = config.getInitParameter("USER");
String psw = config.getInitParameter("PASSWORD");
String id= context.getInitParameter("userId");

out.println("Context and InitParameters values :");
out.println("URL: " + url);
out.println("User: " + uid);
out.println("PSW: " + psw);
out.println("User Id : " + id);
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>userId</param-name>
<param-value>bipul</param-value>
</context-param>
</web-app>

Output :

When you will execute the above example you will get the output as :

Download Source Code