A simple HelloWorldServlet demonstrating usage of @WebInitParam annotation for setting initialization parameters.
Output of the program :
package com.hubberspot.javaee; import java.io.IOException; import java.io.PrintWriter; 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; // @WebServlet annotation has a initParams field which takes // in initialization parameters for a servlet. // @WebInitParam annotation takes in a name and value for the // initialization parameters for the current Servlet. @WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" } , initParams = { @WebInitParam(name = "user" , value = "Jonty") }) public class HelloWorldServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<body>"); out.println("<h2>Hello " + getServletConfig().getInitParameter("user") + "</h2>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } }
Output of the program :