Home Java Javaee6 How to use web.xml in Servlet 3.0


Share on Google+Share on Google+

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.

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 :


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"},
@WebInitParam(name="URL", value="jdbc:mysql://"),
@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 

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);


<?xml version="1.0" encoding="UTF-8"?>

Output :

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

Download Source Code


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 22, 2011

Related Tutorials

Ask Questions?    Discuss: How to use web.xml in Servlet 3.0  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image