public
void init(ServletConfig config) throws ServletException
The
Servlet container calls the init method, once the Instance for the
servlet is created. The servlet won't process any service request
until the init method finish.
The servlet container
cannot place the servlet into service if the init method
a. Throws a
ServletException
b. Does not return
within a time period defined by the Web server
A
servlet that cannot complete its initialization process should throw
UnavailableException.
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/ServletInit"> <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>ServletInit</servlet-name> <servlet-class>ServletInit</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>ServletInit</servlet-name> <url-pattern>/ServletInit</url-pattern> </servlet-mapping> </web-app>
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletInit 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); } }
Related
Links
After
a servlet properly initialized, the servlet container use it to
handle client requests. In the case of an HTTP
request, the objects provided by the container are of types
HttpServletRequest and HttpServletResponse.
No comments:
Post a Comment