Wednesday, 16 July 2014

GetServletConfig() : Get servlet configuration

public ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

<%@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>

<?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>

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




Related Links



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment