Thursday, 14 August 2014

getInitParameter (String name)

public String getInitParameter(String name)
Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/ServletContextParam">
            <input type="submit">
        </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>ServletContextParam</servlet-name>
        <servlet-class>ServletContextParam</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContextParam</servlet-name>
        <url-pattern>/ServletContextParam</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>mailId</param-name>
        <param-value>abcabc@gmail.com</param-value>
    </context-param>
    <context-param>
        <param-name>phoneNum</param-name>
        <param-value>1234567890</param-value>
    </context-param>
</web-app>

ServletContextParam.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletContextParam extends HttpServlet {
 @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        
        try(PrintWriter out = res.getWriter()){
           String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
            String footer = "</h1> </body>" +
                    "</html>";
        
            ServletContext context = req.getServletContext();
            
            String mailId = context.getInitParameter("mailId");
            String phoneNum = context.getInitParameter("phoneNum");
            
            out.println(header);
            out.println("mail:" + " " + mailId +"<br />");
            out.println("Phone: " + phoneNum);
            out.println(footer);
        }
    }

}

Output







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment