Sunday 22 June 2014

what is the use of servlet config object ?

A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

header.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Servlet Config</title>
    </head>
    <body>
        <form method="get" action="/servlet/ServletConfigParam">
            <input type="submit" value="Click Me">
        </form>
    </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ServletConfigParam</servlet-name>
        <servlet-class>ServletConfigParam</servlet-class>
        <init-param>
            <param-name>Author</param-name>
            <param-value>Krishna</param-value>
        </init-param>
        <init-param>
            <param-name>Book</param-name>
            <param-value>Self Learning Java</param-value>
        </init-param>
        <init-param>
            <param-name>URL</param-name>
            <param-value>self-learning-java-tutorial.blogspot.com</param-value>
        </init-param>    
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletConfigParam</servlet-name>
        <url-pattern>/ServletConfigParam</url-pattern>
    </servlet-mapping>
</web-app>

ServletConfigParam.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletConfigParam extends HttpServlet {
 @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       PrintWriter out = res.getWriter();
       res.setContentType("text/html");
       
       /* Get the Servlet Config Object */
       ServletConfig conf = getServletConfig();
       String author = conf.getInitParameter("Author");
       String book = conf.getInitParameter("Book");
       String url = conf.getInitParameter("URL");
       String str = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />" +
                    "Author :" + author +"<br />" +
                    "Book : "+ book +"<br />" +
                    "URL : " + url +
                    "</h1> </body>" +
                    "</html>";
       out.println(str);
   }     
}

Output










                                                             Home

No comments:

Post a Comment