Servlet 3 initialisation parameter annotation @WebInitParam

We will show how you can use the servlet 3 initialisation parameter annotation @WebInitParam to inject initialisation parameters in our servlet. We can configure our servlet entirely with annotations which means no more web.xml which is awesome.

Project structure

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       |--resources
|       |--webapp

Maven Dependency


Servlet 3 initialisation parameter annotation

The @WebInitParam annotation is used to specify init parameters for a servlet or filter. The servlet 3 initialisation parameter takes a required name and value. You can add a description but this is rather informative. In the initialisation method init() we can get our init parameter using the servletConfig.getInitParameter() method.

package com.memorynotfound;

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

        value = "/example",
        initParams = {
                @WebInitParam(name = "email", value = "[email protected]", description = "Email from webmaster"),
                @WebInitParam(name = "phone", value = "xxxx/xx.xx.xx", description = "Phone webmaster")
        description = "Servlet 3 initialisation parameter annotation example: @WebInitParam")
public class ExampleServlet extends HttpServlet{

    private String email, phone;

    public void init(ServletConfig config) throws ServletException {
        email = config.getInitParameter("email");
        phone = config.getInitParameter("phone");

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.write("<h2>Servlet 3 initialisation parameter annotation example: @WebInitParam</h2>");
        out.write("<p><strong>E-mail: </strong>" + email + "</p>");
        out.write("<p><strong>Phone: </strong>" + phone + "</p>");



URL: localhost:8080/init-param/example

servlet 3 initialisation parameter annotation example



You may also like...