Sie sind auf Seite 1von 70

JAVA SERVLET TECHNOLOGY

A Servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.http.servlet are two packages which provided interface and classes for writing servlets. All the servlet must implement servlet interface ,which defines life cycle method When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services. HTTP Servlet typically used to: 1. Provide the dynamically contents which get the result from the server. 2. Process are used to store the data which is submitted by the HTML. 3. Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers. GENERIC SERVLET CLASS CONTAINS FIVE METHODS The generic servlet is the base class of servlet which contains five methods 1.init() method:- Init() is called only once by the servlet container in its whole lofecycle the life of a servlet. The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred. 2.Service() method :- This method defined as public void service as (ServletRequest req, ServletResponse res) which throws ServletException, as IOException .If once the servlet starting getting the requests, the service() method is called by the servlet container to respond. 3.getservlet config():- This method is defined as public ServletConfig getServletConfig() this method contain initialization and startup of the servlet and returns the Servlet Config object 4.getservlet info():- This method is defined as public String getServletInfo() The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. 5.destroy():- This method is defined as public destroy().this method is called when want to close the servlet. LIFE CYCLE OF SERVLET The life cycle of a servlet is controlled by the container in which the servlet has been deployed. The life cycle of a servlet can be categorized into four parts:

1.

Loading and instantiation:-The servlet container loads the servlet during startup or when the first request is made .After loading of servlet container create the instance of the servlet 2. Initialization:-When creating the instances,after that the servlet container calls the init() method .then passes the servlet initialization parameters to the init() method. init() method is called once through out the life cycle of servlet 3. Servicing the request :-After successfully initialization ,servlet container call the service method for servising any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object 4. The servlet Destroying :-If the servlet is no longer required for servicing any request, the servlet container will calls the destroy() method . ADVANTAGES OF JAVA SERVLET Java servlet provide various advantages to build a server side programming. Following are the advantages of java

1.

Portable:- As servlets are written in java and follow APIs of java so they are very high portable over operating systems and serve implementations. 2. Efficient:- As compared to CGI applications servlet is more efficient 3. Extensibility:-The servlet API is designed in such a way that it can be easily extensible. As for now the servlet API support Http Servlets, but in later it can be extended for another type of servlet 4. Safety:- as java is safe servlets are also safe ,garbage collection prevent the leakage of memory and exception handling throws the exceptions for the errors. BASIC SERVLET STRUCTURE import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servletname extends HttpServlet { public void doGet (HttpRequest request,HttpResponse response) throws ServletException, IOException { //code for business logic //use request object to read client request //user response object to throw output back to the client }//close do get } Servlet life cycle include mainly four steps init()--->service()--->doGet() or doPost()--->destroy

A SERVLET PROGRAM (using its life cycle)

//servlet program using its life-cycle import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Testservlet extends HttpServlet { int i; public void init() trows ServletException { i=0; //initializing i value } //incrementing i value in doGet method public void doGet(HttpServletRequest request, HttpServletReponse response) throws IOEXception ,ServletException { response.setContentType("text/html"); PrintWriter out= resonse.getWriter(): if (i==0) { out.println("<html>"); out.prinln ("<head>"); out.println ("<title> Hello world </title>"); out.println ("</head>"); out.println ("<body>"); out.println ("<h1> value of i is initialized in init method </h1>"+"<h1>" + i + "</h1>" out.println("</body>"); out.println ("</html>"); } i = i+; if ((i == 10) { out.println("<html>"); out.println("<head>"); out.println ("<title> HEllo world</title>"); out.println ("</head>"); out.println ("<body>"); out.println ("<h1> i's value reaches 10 hence calling destroy method to reset it </h1>' + "<h1>" + "</h1>"); out.println ("</body>") out.println ("<html>"); destroy(); //call destroy method if i=10 } if (i<10) //display increment value of i { out.prinln("<html>");

out.prinln("<head>"); out.prinln("<title> Hello world </title>"); out.prinln("<head>"); out.prinln("<body>"); out.prinln("<h1> value of i incremented in doGet </h1>" + "<h1>" + i + "<h1>"); out.prinln("</body>"); out.prinln("</html>"); } } public void destroy()//reset i value here { i=0; } } RUNNING SERVLET To run servlet first install and configure the server on your system. web server is required to install to run the servlet. To compileAnd Run: javac ExampServlet.java Servlets can be called directly by typing their uniform resource locator (URL) into a browser's location window after you've started the server. Servlets can also be invoked from an HTML form by specifying their URL in the definition for a Submit button, for example. Servlets can be called by any program that can open an hypertext transfer protocol (HTTP) request. What is web.xml file? Web. xml file also called "web Deployment descriptor" allows us to configure our web application inside the Servlet containerHere we can specify the name of our web application, define our Java Servlets, specify initialization parameters for Servlets, define tag libraries, and a whole lot more. This file is placed inside the /WEB-INF folder. we use two of the features of 'web.xml' file; name of Servlet and the Servlet mapping to a URL. This will allow us to access our Servlet using a URL like /TestServlet.

<?xml version="1.0"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>TestServlet</servlet-name>

<servlet-class>servlets.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/TestServlet</url-pattern> </servlet-mapping> </web-app> To run a Servlet Now we need to start Tomcat server. Type the following command at DOS prompt and hit Enter to start the Tomcat server: C:\apache_tomcat_6.0.14\bin\startup Now open your browser and point to this address: http://localhost:8080/star/Testservlet. You should a get response like following image in your browser window: SUMMARY We began with the introduction to Java Servlets and learned that Serlvets are simple Java classes that implement javax.servlet.Servlet interface. In practice, we will most probably do that by extending javax.servlet.GenericServlet or javax.servlet.http.HttpServlet classes. By above discussions we get know that servlet is efficient and extensible as it store once .

Introduction of Servlet Advantages over CGI USAGE

javax.servlet and its subpackages Life Cycle Method of servlet Non Life Cycle Method of Servlet Interface

How to run the Servlet program First Servlet Program javax.servlet.http.HttpServlet Implementation of Httpservlet javax.servlet.GenericServlet Implementation of GenericServlet Difference between HttpGet() and HttpPost Commonly used methods of ServletRequest interface

Difference between Attributes and Parameters Commonly used methods of ServletResponse interface Second servlet Program RequestDispatcher Commonly used methods of RequestDispatcher interface Inserting Data into database using servlet Example of RequestDispatcher Fetch data from database in servlet ServletContext and servletConfig Interface Commonly used methods of ServletContext interface Commonly used methods of ServletConfig interface Similarities and Difference between servletContext and ServletConfig Example of UserRegistration and Login State Management Cookies Hidden from Fields URL Rewriting HttpSession Object Commonly used methods of HttpSession sendRedirect Example of sendRedirect Example of ServletContextListener Example of Cookies Example of Hidden form Field Example of Session

Example of Random Redirector How a Servlet Works Six steps to running your first Servlet Example of doGet and doPost Method Obtaining HTTP request Headers Manipulating multiple value parameters Delete data from table by name Fetch Data by Name Fetch All data from database table Update data in database table Insert data from database table

Introduction of Servlet:- A servlet is a server side programming


language .A servlet is a technology provided by Sun Microsystem which facilitate dynammic web applications in java. A software developer may use a servlet to add dynamic content to a Web server using the Java platform. Servlets are protocol and platform independent server-side software components, written in Java. They run inside a Java enabled server or application server, such as the WebSphere Application Server. Servlets are loaded and executed within the Java Virtual Machine (JVM) of the Web server or application server, in much the same way that applets are loaded and executed within the JVM of the Web client. Since servlets run inside the servers, however, they do not need a graphical user interface (GUI). In this sense, servlets are also faceless objects. The term servlet is used in two different context with two different meanings:1:-As a technology,it represents set of classes and interfaces provided by Sun microsystem which facilitate developmant of dynammic web applications. 2:-As a web application,a servlet is a java class that is defined using servlet API's for processing request in a web application.

Advantages over CGI:CGI was an protocol that specifies a standard mode of communication between web servers and CGI script.

--Ececution of CGI script was process bases i.e; for each request a new process was started by the web server.Process based execution limits the scalability of the application. --CGI scripts were platform dependent. Servlet as a technology of web application development remove both the problems associated with CGI by provide a thread based execution model and platform dependent components.

USAGE:Servlets are most often used to manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer. provide dynamic content such as the results of a database query process or store data that was submitted from an HTML form

javax.servlet and its subpackages:The javax.servlet and javax.http.servlet are two packages which provided interface and classes for writing servlets. These contains classes and interfaces of servlet API.At the core of servlet API is an interface named javax.servlet.Servlet.This interface provides life cycle methods of a servlet.

Life Cycle Method of servlet:1) init():-This method is invokes only one's just after a servlet object is created.It is used by the server to provide the reference of an object of type ServletConfig to the servlet.javax.servlet.ServletConfig is an interface of servlet API implementation of which is provided by server vendor. syntax:public void init(ServletConfig config); 2)service():- This method is invoked by the server each time a request for the servlet is received.It is used by the application developer to process request and generate dynammic contents. Syntax:public void service (ServletRequest request,ServletResponse response) throws ServletException,IOException ;

In this method web server provides the reference of object's of type ServletRequest and ServletResponse to the servlet.ServletRequest and ServletResponse are interfaces of servlet API implemantation of which are provided by server vendor.ServletRequest and ServletResponse object defines a standard mode of communication between webserver and servlet. 3) destroy():- It is invoked only one's just before a servlet is unloaded. Syntax:public void destroy();

Non Life Cycle Method of Servlet Interface:getServletConfig():- It is used by the application developers to obtain the reference of ServletConfig object from the servlet. Syntax:public ServletConfig getServletConfig(); getServletInfo():- This method is used by the application developer to describe their servlet's. Syntax:public String getServletInfo();

First Servlet Program:- In order to compile a servlet, jar file containing


servlet API classes and interfaces need to be available in the classpath.Servlet API classes and interfaces are not provided by sun microsystem as part of standard java library.These are provided by webserver and application vendors i.e; in order to compile servlets ,the web server and the application server need to be installed. index.html:-

<html> <head> <title>First web application</title> </head> <body> <form action="get" method="firstServlet"> Name<input type="text" name="txtName"> <br> <input type="submit" value="submit"> </form>

web.xml:-

<web-app> <servlet> <servlet-name>g1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>g1</servlet-name> <url-pattern>firstServlet</url-pattern> </servlet-mapping> </web-app> FirstServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { String name=request.getParameter("txtName"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Welcome,"+name); out.close(); } }

javax.servlet.http.HttpServlet:- This class extends GenericServlet and


defines method for each Http request. Commonly used methods of this class are doGet() and doPost() which are used to process http get and post request respectively. Syntax:1:- public void doGet(HttpservletRequest request,HttpServletResponse response)throws ServletException,IOException ;

Parameters: response - HttpServletResponse that encapsulates the response from the servlet request - HttpServletRequest that encapsulates the request to the servlet Throws: IOException if detected when handling the request Throws: ServletException if the request could not be handled 2:public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException;

Parameters: request - HttpServletRequest that encapsulates the request to the servlet response - HttpServletResponse that encapsulates the response from the servlet Throws: IOException if detected when handling the request Throws: ServletException if the request could not be handled

Implementation of Httpservlet:-

public class HttpServlet extends GenericServlet { public void service(ServiceRequest request,ServiceResponse response) throws ServletException,IOException { HttpServletRequest req=(HttpServletRequest)request ; HttpServletResponse res=(HttpServletResponse)response ; service(req,res); } protected void service(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException { request type is checked and doGet() and doPost() etc methods are invoked. } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {} public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {} -

javax.servlet.GenericServlet:-This is an abstract class that implements


servlet interface and defines all its method except service(). This class is used as a based class of user define servlets. In web application HTTP protocol is used for communicating with clients and application. This protocol supports following type of requests:1) Get 2)Post 3)Head 4)Trace 5)Connect 6)put 7)delete 8)option get and post are used to request contents from the server and all other are used for connection setup and management. Implementation of GenericServlet:-

public abstract class GenericServlet implements Servlet { private ServletConfig config ; public void init(ServletConfig config) { this.config=config; init(); } public void init() { /*utility method that can be overrided by application developers to perform initialization*/ } public void display() {} public ServletConfig getServletConfig() { return config ; } = = }

Difference between HttpGet() and HttpPost() :Conventional difference:- getRequest is used for requesting static contents and postRequest is used for requesting dynammic contents. Technical Difference:1) In case of getRequest request data is sent as part of header.Size of http packet header is fixed,hence only limited amount of data can be send using getRequest. In case of postRequest request data is sent as part of paket body.Size of http packet body can be unlimited,hence unlimited amount of data can be sent using postRequest. 2) In case of getRequest request parameters are appended to the url and are visible in the address bar of the browser. In case of postRequest request parameters are not appended to the url,hence they are not shown in the address bar of the browser. 3) In case of getRequest request is sent as submitted by the user whereas in case of postRequest it is sent in an encrypted form.

Commonly used methods of ServletRequest interface:-

getParameter():-is used to receive the value of request parameter Syntax:public String getParameter(String pName); getParameterNames():-Returns an enumeration for the name of all request parameters. Syntax:public Enumeration getParameterNames(); setAttribute():- is used to save an attribute in the request scope Syntax:public void setAttribute(String name,Object value); getAttribute():- is used to obtain the value of an attribute. Syntax:public Object getAttribute(String name); getAttributeNames():- is used to find out the name of attributes saved in request scope. Syntax:public Enumeration getAttributeNames(); removeAttribute():- is used to remove an attribute from the request scope. Syntax:public boolean remove(String Name); getInputStream():- is used to obtain an inputStream to read request data. Syntax:public InputStream getInputStream();

Difference between Attributes and Parameters:1) Parameter represents data received as part of request whereas attributes represent data stored by servlet for another servlet involved in processing the same request.

2) Parameters represent string data whereas attributes can be any type of objects. 3) Parameters can only be used by the servlet whereas attributes are stored,removed,replaced and read by the servlets. Attributes are used by the servlets to share information with other servlets,participating in processing the same request.

Commonly used methods of ServletResponse interface:setContentType():- is used to specify content type of the response. Syntax:public void setContentType(String MIMEtype); MIME type:- represents format of contents provided to browser by a server.A MIME type is represented by string having following :format:- major part/minor part eg;- text/plain,text/html,image/jpg etc. getWriter():- Returns the reference of Printwriter object to write data to the response. Syntax:public PrintWriter getWriter(); getOutputStream():- Returns an output stream object to write data to the response. Syntax:public OutputStream getOutputStream();

Second servlet Program:-This program show you how to open the data in
the ms-word and the ms-excel.

ExcelSevlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ExcelServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("application/vnd.ms-exce"); PrintWriter out=response.getWriter(); out.println("Name\tCourse\tFee"); out.println("Amit\tJava\t9000"); out.println("Amit\tJava\t9000"); out.println("Amit\tJava\t9000"); out.println("\tTotal\t=Sum(C2:C4)"); out.close(); } }

WordServlet.java:import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WordServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("application/msword"); PrintWriter out=response.getWriter(); out.println("Name\tCourse\tFee"); out.println("Amit\tJava\t9000"); out.println("Amit\tJava\t9000"); out.println("Amit\tJava\t9000"); out.close(); } }

index.html:-

<html> <head> <title>FirstWeb application</title> </head> <body> <a href="wordFormat"> Word Format</a> <a href="excelFormat"> Excel Format</a> </body> </html>

web.xml:<web-app> <servlet> <servlet-name>van</servlet-name> <servlet-class>WordServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>van</servlet-name> <url-pattern>wordFormat</url-pattern> </servlet-mapping> <servlet> <servlet-name>vani</servlet-name> <servlet-class>ExcelServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name> vani</servlet-name> <url-pattern>excelFormat</url-pattern> </servlet-mapping> </web-app

RequestDispatcher:javax.servlet.RequestDispatcher is an interface of servlet API ,implemantation of which is provided by the vendor. RequestDispatcher object is used by the servlet to forward the request to another web resource to include the contents of another web resource. Commonly used methods of RequestDispatcher interface:include():- is used to include the contents of a resource with the response of current servlet. Syntax:-

public void include (ServletRequest request,ServletResponse response) throws ServletException,IOException ; forward():- is used to forward request to another servlet ,jsp or html page. Syntax:public void forward(ServletRequest request,ServletResponse response) throws ServletException,IOException ; Note:- In case of forward, contents are generated only by the forwarded resource that is forwarding servlet doesn't generate response. getRequestDispatcher():- Method of ServletRequest interface is used to obtain a request dispatcher object for a resource. Syntax:public RequestDispatcher getRequestDispatcher(String URL of resource); Inserting Data into database using servlet:-This program shows you how to insert the data in the database table via JDBC in servlet. index.html:<html> <head> <title>Register User</title> </head> <body> <b>Register Yourself</b><br> <form method="get" action="registerServlet"> Name<input type="text" name="txtName"><br> Password<input type="password" name="password"><br> <input type="submit" value="submit"> </form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>gauri</servlet-name> <servlet-class>RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>gauri</servlet-name> <url-pattern>registerServlet</url-pattern> </servlet-mapping> </web-app> RegisterServlet.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtName"); String password=request.getParameter("password"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("insert into LoginDetails values(?,?)"); stmt.setString(1, name); stmt.setString(2, password); int i=stmt.executeUpdate(); out.println("<b>You are successfully Registered</b>"); con.close(); } catch(Exception e) { out.println("<b>Registration failed</b>"); out.println("<b>Error:</b>" +e); } } }

Example of RequestDispatcher:- RequestDispatcher object is used by


the servlet to forward the request to another web resource to include the contents of another web resource. LoginServlet.java:import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { try { String user1=request.getParameter("txtName"); String password1=request.getParameter("txtPassword"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","gaurav"); PreparedStatement stmt=con.prepareStatement("select * from infologin where name=? and password=?"); stmt.setString(1,user1); stmt.setString(2,password1); ResultSet rset=stmt.executeQuery(); if(rset.next()) out.println("Welcome," +user1); else { out.println("<b>Invalid username and password !</b><br>"); RequestDispatcher rd=request.getRequestDispatcher("index.html"); rd.include(request,response); } out.close();con.close(); } catch(Exception e) {System.out.println(e); } } } index.html:-

<html> <head> <title> third web applicatin</title> </head> <body> <form method="get" action="loginServlet"> Name<input type="text" name="txtName"> <br> Password<input type="password" name="txtPassword"> <br> <input type="submit" value="submit"> </form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name> v1 </servlet-name> <servlet-class> LoginServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> v1 </servlet-name> <url-pattern> loginServlet </url-pattern> </servlet-mapping> </web-app>

Fetch data from database in servlet:-This program shows you how to


fetch all the rows from the database table via JDBC using servlet. ServletFetch.java:-

import import import import

java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletFetch extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","gaurav"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("Select * from logindetails"); while(rs.next()){ out.println("<body><table><th>") ; out.println("Name" + " " + "password" +"</th>" +"<br>"); out.println( rs.getString(1) + " " + rs.getString(2) + "<br>"); } } catch (Exception e){ System.out.println(e); } } } <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>ServletFetch</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>ServletFetchingDataFromDatabase</url-pattern> </servlet-mapping> </web-app> index.html:-

<html> <head> <title>Fetch data</title> </head> <body> <a href="ServletFetchingDataFromDatabase">click here</a> </body> </html>

ServletContext and servletConfig Interface:Servlet Context:- ServletContext is an interface of servlet API, implementation of which is provided by the vendor.An object of type ServletContext is created by the server at the time of application deployment.ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it.The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. This object has following uses:-

1)It is used by the server to provide application scope initialization parameters to the servlet. 2)It is used by the servlet to share information in the form of attributes accross multiple request. 3)It is used by the servlet to interact with the web server. ServletConfig:- For each servlet webserver creates an object of type ServletConfig.This object has following two use:1)It is used by the server to provide the reference of ServletContext to the servlet 2)It is used by the server to provide servlet specific initialization parameters to the servlet.

Commonly used methods of ServletContext interface:getInitParameter():- is used to obtain the value of an initialization parameter. Syntax:public String getInitParameter(String pName); getInitParameterNames():- Returns an enumeration for the name of all initialization parameters stored in ServletContext object. Syntax:public Enemeration getInitParameterNames(); setAttribute():- is used to store an attribute in application scope. Syntax:public void setAttribute(String name,Object value); getAttribute():- is used to obtain the value of an attribute. Syntax:public Object getAttribute(String name); getAttributeNames():- Returns an enumeration for all the attributes saved in application scope. Syntax:public Enumeration getAttributeNames();

removeAttribute():- is used to remove an attribute from the application scope. Syntax:public boolean removeAttribute(String name); getContext():- is used to obtain the reference of ServletContext object of the specify application. Syntax:public ServletContext getContext(String appName); getRequestDispatcher():- is used to obtain a requestDispatchet object. Syntax:public RequestDispatcher getRequestDispatcher(String url of Resource); getRealPath():- is used to find out actual path of resource an a server. Syntax:public String getRealPath(String url);

Commonly used methods of ServletConfig interface:getServletContext():-is used to obtain the reference of sevletContext object. Syntax:public ServletContext getServletContext(); getInitParameter():- is used to obtain the value of initialization parameter. Syntax:public String getInitParameter(String name); getInitParameterNames():- Returns an enumeration for the name of initialization parameters stored in ServletConfig. Syntax:public Enumeration getInitParameterNames(); Similarities and Difference between servletContext and ServletConfig:Similarities:-

1. Both these interfaces are in same javax.servlet package


2. The vendors of Web Server (which support servlet technology) provide the implementation classes for theses two interfaces. Differences : 1. Only one ServletContext object will existed for one Web Application. One Servlet Configuration object existed per a Servlet in a Web Application. 2. A ServletContext object will be shared by all the Servlets which are present in Web Application. Every Servlet of a Web Application contain individually a Servlet Configuration object. 3. A ServletContext defines a set of methods that a Servlet uses to communicate with its Servlet Container. The ServletConfig is to pass configuration information to a Servlet. The Server passes an object that implements the ServletConfig interface to the Servlet's init() method. 4. ServletContext object is used to access the Context parameters specified in web.xml file. A Servlet Config object is used to access the Initialization parameters specified for particular Servlet in a web.xml file.

Example of UserRegistration and Login:-In this example,first the user


need to register yourself and after that login using the servlet and JDBC.. index.html:-

<html> <head> <title>Login Test web Application</title> </head> <body> <form method="post" action="loginServlet"> Name<input type="text" name="txtName"><br> Password<input type="password" name="password"><br> <input type="submit" value="submit"> </form> <b>New User!</b><br> <a href="register.html">Register Yourself</a> </body> </html> <html> <head> <title>Login Test web Application</title> </head> <body>

<form method="post" action="loginServlet"> Name<input type="text" name="txtName"><br> Password<input type="password" name="password"><br> <input type="submit" value="submit"> </form> <b>New User!</b><br> <a href="register.html">Register Yourself</a> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>gau</servlet-name> <servlet-class>LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>gau</servlet-name> <url-pattern>loginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>gauri</servlet-name> <servlet-class>RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>gauri</servlet-name> <url-pattern>registerServlet</url-pattern> </servlet-mapping> </web-app> LoginServlet.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { try {

String name=request.getParameter("txtName"); String password=request.getParameter("password"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","gaurav"); PreparedStatement stmt=con.prepareStatement("select * from logindetails where name=? and password=?"); stmt.setString(1,name); stmt.setString(2,password); ResultSet rset=stmt.executeQuery(); if(rset.next()) out.println("Welcome," +name); else { out.println("<b>Invalid username and password !</b><br>"); RequestDispatcher rd=request.getRequestDispatcher("index.html"); rd.include(request,response); con.close(); }} catch(Exception e) { System.out.println(e); } } } RegisterServlet.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtName"); String password=request.getParameter("password"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","gaurav"); PreparedStatement stmt=con.prepareStatement("insert into LoginDetails values(?,?)"); stmt.setString(1, name);

stmt.setString(2, password); int i=stmt.executeUpdate(); out.println("<b>You are successfully Registered</b>"); con.close(); } catch(Exception e) { out.println("<b>Registration failed</b>"); out.println("<b>Error:</b>" +e); } } }

State Management:- Http the protocol that is used for communication . A


Web server is a stateless protocol ,it means that it cannot persist the information. It always treats each request as a new request.that is for each request a new Http connection is made. The disadvantage of stateless protocol is that server fails to recognize that a series of requests coming from a user are logically related and represents a single operation from user point of view. Problem of State management deals with the maintainance of state between multiple request of a client.Over the time following four methods are divided for maintaining state:1)Cookies 2)Hidden from fields 3)URL rewriting 4)HttpSession objects.

Cookies:- A cookie represents textual information in the form of key value pair
that is sent by the server as part of the response to the client machine and is sent by the clien to the server with substituent requests.Cookies provide a simple mechanism for maintaining information between requests. Cookies can be of two types:1)Persistent cookies 2)Non-persistent cookies

1)Persistent cookies:- Persisrent cookies remain valid for multiple


session.They are stored by the browser in a text file on the client machine.

2)Non-persistent cookies:- Non-persistent cookies remain valid only for a


single session.They are stored by the browser in its cache and are discarded when communication with the server is terminated. javax.servlet.http.Cookie:- Class provides object representation of cookies. A cookie object can be created using following constructor:public Cookie(String key,String value);

Hidden from Fields:- This is a browser independent approach of maintaining


state between requests in a web applicaion.In this approach information to be persistent is stored in invisible text fields which are added to the response page.When a request is submitted from the response page value of invisible text fields is submitted as request parameters.

Disadvantage:1) This approach can be used if input forms are used for submitting request. 2) Only textual informaton can be persistent.

Url Rewriting:URL rewriting is another way to support state tracking. With URL rewriting, the parameter that we want to pass back and forth between the Web browser and client is appended to the URL. URL rewriting is the lowest common denominator of session tracking, and is used when a client does not accept cookies. We modified the CookieServlet to implement the same state tracking mechanism technique, but by using URL rewriting.URL Rewriting can be used in place where we don't want to use cookies.The URL Rewriting is used for maintaining the session. HttpSession Object:-(javax.servlet.http.HttpSession) :- Servlet API provides HttpSession interface ,implementation pf which is provided by vendor. An object of type HttpSession can be created by the server per user.This object can be used by the application developer to store user specific information in the form of attributes between requests. Commonly used methods of HttpSession:setAttribute():public void setAttribute (String name,Object value); getAttribute():-

public Object getAttribute(String name); getAttributeNames():public Enumeration getAttributeNames(); removeAttribute():public boolean removeAttribute(); isNew():- is used to find out whether session object is created in the current request or not. public boolean isNew(); setMaxInactiveInterval():- is used to specify maximum time in seconds for which a session object is maintained on the server even if no request is received from the client. public void setMaxInactiveInterval(int seconds); invalidate():- is used to release the interaction/session. public void invalidate();

sendRedirect:- Method of ServletResponse,redirect is used to request the


browser to send a fresh request for the given url. Servlet Redirect forces the browser to do work.

Syntax:public void sendRedirect (String URL of resource); Example of sendRedirect:index.html:<html> <head></head> <body> <a href="welcomeServlet">Send URL Other Server</a> </body> </html>

web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> </web-app>

WelcomeServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.sendRedirect("http://www.facebook.com/"); } }

Example of RequestDispatcher:index.html:-

<html> <head><title>First Servlet</title></head> <body> <a href="application">Servlet One of Application</a> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>application</url-pattern> </servlet-mapping> <servlet> <servlet-name>s1</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>servletTwo</url-pattern> </servlet-mapping> </web-app> FirstServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { System.out.println("Servlet one of application invoked ,forwading request."); ServletContext ctx=getServletConfig().getServletContext(); System.out.println("Config and Context"); ServletContext ctxofapp2=ctx.getContext("ReciverDispatcher"); System.out.println("Context"); RequestDispatcher rd=ctxofapp2.getRequestDispatcher("/servletTwo"); System.out.println("RequestDispatcher"); rd.forward(request,response); } } SecondServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { System.out.println("Servlet two of app2 invoked, generating response"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<b>It is generated by servlet two of application 2</b>"); out.close(); } }

Example of ServletContextListener:index.html:-

<html> <head> <title>My Second Web Application</title> </head> <body> <form method="get" action="listenerPage"> <b>Name<input type="text" name="textName"> <br><input type="submit" value="Login"></form> </body> </html> web.xml:-

<web-app> <listener> <listener-class>MyListener</listener-class> </listener> <servlet> <servlet-name>s1</servlet-name> <servlet-class>LoginServlet</servletclass> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <urlpattern>listenerPage</url-pattern> </servlet-mapping> <servlet> <servletname>s2</servlet-name> <servlet-class>LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <urlpattern>logoutServlet</url-pattern> </servlet-mapping> <servlet> <servletname>s3</servlet-name> <servlet-class>AdminServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s3</servlet-name> <urlpattern>adminServlet</url-pattern> </servlet-mapping> </web-app> AdminServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class AdminServlet extends HttpServlet

{ public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { ServletContext ctx=getServletConfig().getServletContext(); int t=((Integer) ctx.getAttribute("total")).intValue(); int c=((Integer) ctx.getAttribute("current")).intValue(); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Welcome, Admin"); out.println("<br>Count of user...."); out.println("<br>Total user: "+t); out.println("<br>Current user: "+c); out.println("<br><a href=adminServlet>Refresh Counter</a>"); out.close(); } }

LoginServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { String name=request.getParameter("textName"); request.getSession(); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Welcome ,"+name); out.println("<br><a href=logoutServlet>LogOut</a>"); out.close(); } } LogoutServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws

ServletException,IOException { HttpSession session=request.getSession(); session.invalidate(); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("You are successfully logout"); out.println("<br><a href=index.html>Login Again</a>"); out.close(); } } MyListener.java:-

import javax.servlet.*; import javax.servlet.http.*; public class MyListener implements ServletContextListener,HttpSessionListener { ServletContext ctx; public void contextInitialized(ServletContextEvent e) { ctx=e.getServletContext(); ctx.setAttribute("total",new Integer(0)); ctx.setAttribute("current",new Integer(0)); } public void contextDestroyed(ServletContextEvent e) {} public void sessionCreated(HttpSessionEvent e) { int t=((Integer) ctx.getAttribute("total")).intValue(); int c=((Integer) ctx.getAttribute("current")).intValue(); ++t; ++c; ctx.setAttribute("total",new Integer(t)); ctx.setAttribute("current",new Integer(c)); } public void sessionDestroyed(HttpSessionEvent e) { int c=((Integer) ctx.getAttribute("current")).intValue(); --c; ctx.setAttribute("current",new Integer(c)); } }

Example of Cookies:-A cookie represents textual information in the form of


key value pair that is sent by the server as part of the response to the client machine and is sent by the clien to the server with substituent requests.Cookies provide a simple mechanism for maintaining information between requests.This example shows you how to create the cookies using the JDBC and servlet.

index.html:<html> <head> <title>My Second Web Application</title> </head> <body> <form method="get" action="application"> <b>Name<input type="text" name="txtName"> <br><input type="submit" value="Login"></form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>application</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>toursevlet</url-pattern> </servlet-mapping> </web-app> TourServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { String name="Guest"; Cookie cks[]=req.getCookies(); if(cks!=null) name=cks[0].getValue();

res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Sorry,"+name); out.println("<br> Site is down for routine maintainance,pls visit again later..."); out.close(); } } WelcomeServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("txtName"); Cookie cks=new Cookie("username",name); cks.setMaxAge(6000); res.addCookie(cks); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("welcome," +name); out.println("<br><form action=toursevlet>"); out.println("<br><input type=submit value=\"Take a tour\">"); out.println("<br></form>"); out.close(); } }

Example of Hidden form Field:-This is a browser independent approach


of maintaining state between requests in a web applicaion.In this approach information to be persistent is stored in invisible text fields which are added to the response page.When a request is submitted from the response page value of invisible text fields is submitted as request parameters. index.html:<html> <head> <title>My Second Web Application</title> </head> <body> <form method="get" action="application"> <b>Name<input type="text" name="txtName"> <br><input type="submit" value="Login"></form> </body>

</html>

web.xml:<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>application</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>toursevlet</url-pattern> </servlet-mapping> </web-app> TourServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("userName"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Sorry,"+name); out.println("<br> Site is down for routine maintainance,pls visit again later..."); out.close(); } }

WelcomeServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("txtName"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<br><form action=toursevlet>"); out.println("<br><input type=hidden name=userName value=\""+name+"\">"); out.println("<br><input type=submit value=\"Take a tour\">"); out.println("<br></form>"); out.close(); } }

Example of Session:-This example shows you how we use the session in the
Servlet. index.html:<html> <head> <title>My Second Web Application</title> </head> <body> <form method="get" action="application"> <b>Name<input type="text" name="txtName"> <br><input type="submit" value="Login"></form> </body> </html> web.xml:<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>application</url-pattern> </servlet-mapping>

<servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>toursevlet</url-pattern> </servlet-mapping> </web-app> TourServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { HttpSession session=req.getSession(); String name=(String)session.getAttribute("name"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Sorry,"+name); out.println("<br> Site is down for routine maintainance,pls visit again later..."); out.close(); } } WelcomeServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("txtName"); HttpSession session=req.getSession(); session.setAttribute("name",name); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("welcome," +name); out.println("<br><form action=toursevlet>");

out.println("<br><input type=submit value=\"Take a tour\">"); out.println("<br></form>"); out.close(); } }

Example of Random Redirector:- This example shows you how to select


the random url by using the JDBC and the servlet. index.html:-

<html> <head> <title>My Random Site selection application</title> </head> <body> <a href="randomselection">click here to see the result</a> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>RandomSelection</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>randomselection</url-pattern> </servlet-mapping> </web-app> RandomSelection.java:-

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class RandomSelection extends HttpServlet { Random random = new Random(); Vector s1 = new Vector(); public void init() throws ServletException { s1.addElement("http://www.r4r.co.in");

s1.addElement("http://www.facebook.com"); s1.addElement("http://www.santabanta.com"); s1.addElement("http://www.r4rtechsoft.com"); s1.addElement("http://www.yahoo.com"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int siteIndex = Math.abs(random.nextInt()) % s1.size(); String s = (String)s1.elementAt(siteIndex); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", s); } }

How a Servlet Works:- First time when the servlet is requested,then the
servlet is loaded by the sevlet container.After that the servlet forward the user request,processing that request and give the response back to the servlet container,then the servlet container send back the response to the user.After that,the servlet are waiting for the other request ,and stays in memory,until the other request ic come, it will be in the memory until the servlet container sees a shortage of memory.Each time the servlet is requested ,however,the servlet container compares the timestamp of the loaded servlet with the servlet class file.If the class file timestamp is more recent, the servlet is reloaded into memory.This way you don't need to restart the servlet container every time you update your servlet. Six steps to running your first Servlet:- After you have installed and configured weblogic server or any other server.Basically you need to follow six steps to go from writing your servlet to running it.These steps are as follows:1)Create a directory structue,i.e; first you need to create a folder and give the name of that folder,after that you make a new folder under the previous folder and give the name of that folder.The folder name must be "WEB-INF".Put the ..html file parallel to the WEB-INF folder.Under the WEB-INF folder,creater a folder and give the name of that folder.The folder name must be "classes" and put the .xml file parallel to the classes folder.Under the classes folder put all the .java files. 2)Write the servlet source code. You need to import the javax.servlet package and javax.servlet.http package in your source file. 3) Compile the source code.. 4)Start the server. 5)Deploy the application. 6) Call your servlet from a web browser.

Example of doGet and doPost Methods:-

When a servlet is first called from a web browser by typing the url to the servlet in the address bar,POST method is used as the request method.At the server side,the doPost method is invoked.The servlet sends a string saying "The servlet has received a POST.now,click the button below.". The form is sent to the browser uses the GET method.When the user clicks the button to submit the form,a GET request is sent th the server.The servlet then invoked the doGet method,sending a string saying "The servlet has received a GET".Thank you. index.html:-

<html> <head> <title>Application of post and get method</title> </head> <body> <form method="post" action="post"> Name<input type="text" name="txtName"><br> <input type="submit" value="click"> </form> </body> <html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>POstMethod</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>post</url-pattern> </servlet-mapping> <servlet> <servlet-name>s1</servlet-name> <servlet-class>POstMethod</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>get</url-pattern> </servlet-mapping> </web-app> RegisterServlet.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class RegisterServlet extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("The servlet has received a POST."+"now,click the button below"); out.println("<br><a href='get'>Click here</a>"); } public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { String name=req.getParameter("txtName"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("The servlet has received a GET.Thank you."); } }

Obtaining HTTP request Headers:The following example demonstrates how you can use the HttpServletRequest interface to obtain all the header names and sends the header name/value pairs to the browser.

index.html:<html> <head> <title>Application of post and get method</title> </head> <body> <form method="get" action="post"> <input type="submit" value="click"> </form> </body> <html>

web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>post</url-pattern> </servlet-mapping> </web-app>

RegisterServlet.java:import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); Enumeration enumeration=req.getHeaderNames(); while(enumeration.hasMoreElements()) { String header=(String)enumeration.nextElement(); out.println(header+":"+req.getHeader(header)+"<br>"); } } }

Manipulating multiple value parameters:the following example illustrates the use of the getParameterValues method to get all favourite music selected by the user.The code for this servlet is as follows:index.html:-

<html> <head> <title>Check box Demo</title> </head> <body> <form method = "post" action = "music"> <p>Which type of music you like it ? </p>

<input type Rock<br> <input type <input type <input type <input type rock<br> <input type </form> </body> </html> web.xml:-

= "checkbox" name ="favouritemusic" value = "Rock"> = = = = "checkbox" "checkbox" "checkbox" "checkbox" name name name name ="favouritemusic" ="favouritemusic" ="favouritemusic" ="favouritemusic" value value value value = = = = "Jazz">Jazz<br> "hiphop">hiphop.<br> "pop">pop<br> "heavy rock">heavy

="submit" name= "submit">

<web-app> <servlet> <servlet-name>H1</servlet-name> <servlet-class>GetParamValues</servlet-class> </servlet> <servlet-mapping> <servlet-name>H1</servlet-name> <url-pattern>music</url-pattern> </servlet-mapping> </web-app> GetParamValues.java:-

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetParamValues extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] values=request.getParameterValues("favouritemusic"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); if(values!=null) { int length=values.length; for(int i=0;i<length;i++) pw.println("<br>Favourite Music : " + values[i]); } } }

Delete data from table by name:-This example shows you how to delete
the data from the database table by providing the unique name using the JDBC and servlet. index.html:-

<html> <head> <title>Delete Data from database by Name </title> </head> <form action="del" method="get"> UserName<input type="text" name="txtName"><br> <input type="submit" value="delete"><br> </form> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>Delete</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>del</url-pattern> </servlet-mapping> </web-app> Delete.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class Delete extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtName"); try {

Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("delete from emp where name=?"); stmt.setString(1, name); int i=stmt.executeUpdate(); if(i!=0) out.println("<b>You are successfully deleted</b>"); con.close(); } catch(Exception e) { out.println("<b> failed</b>"); out.println("<b>Error:</b>" +e); } } }

Fetch Data by Name:-This example shows you how to fetch the row from
the database table by providing the unique name using JDBC and servlet. index.html:-

<form action="fetch" method="get"> UserName<input type="text" name="txtName"><br> <input type="submit" value="login"><br> </form> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>Fetch</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>fetch</url-pattern> </servlet-mapping> </web-app> Fetch.java:-

import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Fetch extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("txtName"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("Select * from emp where name=? "); stmt.setString(1, name); ResultSet rset=stmt.executeQuery(); out.println("The data is:-"); while(rset.next()) { out.println(rset.getString(1)+"\t"+rset.getString(2)); } } catch(Exception e) { System.out.println(e); } out.close(); } }

Fetch All data from database table:-This example shows you how to
fetch the all rows from the database table by using the JDBC and the servlet. index.html:-

<a href="f1">FetchAll Data</a>

web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FullDataFetch</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>f1</url-pattern> </servlet-mapping> </web-app> FullDataFetch.java:-

import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class FullDataFetch extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("Select * from emp "); ResultSet rset=stmt.executeQuery(); out.println("The data is:-"); while(rset.next()) { out.println(rset.getString(1)+"\t"+rset.getString(2)+"<br>"); } } catch(Exception e) { System.out.println(e); } out.close(); } }

Update data in database table:-This program shows you how to update


the name in the database table by using the JDBC and the servlet. index.html:-

<html> <head> <title>Update Row Data</title> </head> <body> <form action="update"> Old Name<input type="text" name="name"><br> Name<input type="text" name="txtName"><br> Password<input type="password" name="pass"><br> <input type="submit" value="submit"> </form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>Update</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>update</url-pattern> </servlet-mapping> </web-app> Update.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class Update extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { String name=request.getParameter("name"); String name1=request.getParameter("txtName");

String password=request.getParameter("pass"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("update emp set name=?,pass=? where name=?"); stmt.setString(1, name1); stmt.setString(2, password); stmt.setString(3, name); stmt.executeUpdate(); if(true) out.println("<b>You are successfully update</b>"); con.close(); } catch(Exception e) { out.println("<b> failed</b>"); out.println("<b>Error:</b>" +e); } } }

Insert data from database table:-This example shows you how to insert
the data in the database table by using the JDBC and the servlet. index.html:-

<html> <head> <title>Inser data from table</title> </head> <body> <form method="get" action="loginServlet"> Name<input type="text" name="txtName"><br> Password<input type="password" name="password"><br> <input type="submit" value="submit"> </form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>loginServlet</url-pattern> </servlet-mapping> </web-app> InsertServlet.java:-

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class InsertServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtName"); String pass=request.getParameter("password"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("insert into emp values(?,?)"); stmt.setString(1, name); stmt.setString(2, pass); int i=stmt.executeUpdate(); if(i!=0) out.println("<b>You are successfully Registered</b>"); con.close(); } catch(Exception e) { out.println("<b>Registration failed</b>"); out.println("<b>Error:</b>" +e); } }

Play Video song using servlet:-This example shows you how to play the
video song on the servler by using the JDBC and the servlet. using this example. By you can plan the video song on the server. index.html:-

<html> <head> <title>Video application</title> </head> <body> <a href="video">click here</a> </form> </body> </html> web.xml:-

<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>Video</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>video</url-pattern> </servlet-mapping> </web-app> Video.java:-

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Video extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html");

PrintWriter out=res.getWriter(); out.println("<br><embed src='video.mp4'>"); } }

Servlet Interview Questions And Answers

Page 1
Ques: 1 What is a servlet filter? Ans: A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page. Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page. Filters can perform many different types of functions: * Authentication * Logging and auditing * Data compression * Localization The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor : <!--Servlet Filter that handles site authorization.--> <filter> <filter-name>AuthorizationFilter</filter-name> <filter-class>examples.AuthorizationFilter</filter-class> <description>This Filter authorizes user access to application components based upon request URI.</description> <init-param> <param-name>error_page</param-name> <param-value>../../error.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>AuthorizationFilter</filter-name> <url-pattern>/restricted/*</url-pattern> </filter-mapping> Ques: 2 What is a WAR file? Ans: A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into a Web server. The WAR file also includes a Web deployment descriptor file. There are special files and directories within a WAR file. The /WEB-INF directory in the WAR file contains a file named web.xml which defines the structure of the web application. If the web application is only serving

JSP files, the web.xml file is not strictly necessary. If the web application uses servlets, then the servlet container uses web.xml to ascertain to which servlet a URL request is to be routed. One disadvantage of web deployment using WAR files in very dynamic environments is that minor changes cannot be made during runtime. WAR file is created using the standard Java jar tool. For example: cd /home/alex/webapps/mywebapp jar cf ../mywebapp.war * Ques: 3 What is servlet exception? Ans: ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty. ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception. It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class. Packages that use ServletException : * javax.servlet * javax.servlet.http Ques: 4 What is the difference between an application server and a web server? Ans: A web server deals with Http protocols and serves the static pages as well as it can ask the helper application like CGI program to generate some dynamic content. A web server handles the client request and hands the response back to the client. An application server exposes business logic to client applications through various protocols, possibly including HTTP. An application server provides access to business logic for use by client application programs. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a 'built-in' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module, portlets etc. Ques: 5 How can you implement singleton pattern in servlets ? Ans: Singleton is a useful Design Pattern for allowing only one instance of your class. you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor. Ques: 6 Do objects stored in a HTTP Session need to be serializable? Or can it store any object? Ans: It's important to make sure that all objects placed in the session can be serialized if you are building a distributed applicatoin. If you implement Serializable in your code now, you won't have to go back and do it later. Ques: 7 What is deployment descriptor? Ans: Deployment descriptor is a configuration file named web.xml that specifies all the pieces of a deployment. It allows us to create and manipulate the structure of the web application. Deployment descriptor describes how a web application or enterprise application should be deployed. For web applications, the deployment

descriptor must be called web.xml and must reside in a WEB-INF subdirectory at the web application root. Deployment descriptor allows us to modify the structure of the web application without touching the source code. Ques: 8 What is the web container? Ans: The Web container provides the runtime environment through components that provide naming context and life cycle management, security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE. Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies. Ques: 9 Is HTML page a web component? Ans: No! Html pages are not web component, even the server-side utility classes are not considered web components. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Ques: 10 How HTTP Servlet handles client requests? Ans: HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these: * doDelete(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a DELETE request. * doGet(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a GET request. * doOptions(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. * doPost(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a POST request. * doPut(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a PUT request. * doTrace(HttpServletRequest req, HttpServletResponse resp) : Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc. Ques: 11 What are the uses of ServletResponse interface? Ans: ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually. Packages that use ServletResponse : * javax.servlet * javax.servlet.http

* javax.servlet.jsp Ques: 12 What are the uses of ServletRequest? Ans: ServletRequest defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method. A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest. Packages that use ServletRequest : * javax.servlet * javax.servlet.http * javax.servlet.jsp Ques: 13 What is pre initialization of a servlet? Ans: Servlets are loaded and initialized at the first request come to the server and stay loaded until server shuts down. However there is another way you can initialized your servlet before any request come for that servlet by saying <load-onstartup>1</load-on-startup> in the deployment descriptor. You can specify <loadon-startup>1</load-on-startup> in between the <servlet></servlet> tag. Ques: 14 Explain the directory structure of a web application? Ans: The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml file that consist of deployment information. 2. classes directory cosists of business logic. 3. lib directory consists of jar files. Ques: 15 How do servlets handle multiple simultaneous requests? Ans: Servlets are under the control of web container. When a request comes for the servlet, the web container find out the correct servelt based on the URL, and create a separeate thread for each request. In this way each request is processed by the different thread simultaneously. Ques: 16 Can we call a servlet with parameters in the URL? Ans: Yes! We can call a servlet with parameters in the URL using the GET method. Parameters are appended to the URL separated with the '?' with the URL and if there are more than one parameter, these are separated with the '&' sign. Ques: 17 How will you communicate from an applet to servlet? Ans: You can write a servlet that is meant to be called by your applet. Applet-Servlet Communication with HTTP GET and POST : The applet can send data to the applet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string. Communicating with Object Serialization :

Instead of passing each parameter of student information as name/value pairs, we'd like to send it as a true Java object. Upon receipt of the this object, the servlet would add the this to the database. Sending Objects from a Servlet to an Applet : After registering the object in the database. Now the servlet has to return an updated list of registered students that is then returned as a vector of objects. Ques: 18 What is Servlet chaining? Ans: Servlet Chaining is a phenomenon wherein response Object (Output) from first Servlet is sent as request Object (input) to next servlet and so on. The response from the last Servlet is sent back to the client browser. In Servlets, there are two ways to achieve servlet chaining using javax.servlet.RequestDispatcher: 1. Include: RequestDispatcher rd = req.getRequestDispatcher("Servlet2"); rd.include(req, resp); 2. Forward, where req is HttpServletRequest and resp is HttpServletResponse: RequestDispatcher rd = req.getRequestDispatcher("Servlet3"); rd.forward(req, resp); Ques: 19 How do you communicate between the servlets? Ans: Servlets can communicate using the request, session and context scope objects by setAttribute() and getAttribute() method. A servlet can placed the information in one of the above scope object and the other can find it easily if it has the reefrence to that object. Ques: 20 What is the use of setSecure() and getSecure() in Cookies ? Ans: The setSecure(boolean flag) method indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL. The getSecure() method returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.

Page 2
Ques: 21 Why we are used setMaxAge() and getMaxAge() in Cookies ? Ans: The "public void setMaxAge(int expiry)" method sets the maximum age of the cookie. After the specified time the cookie will be deleted. The "public int getMaxAge()" method will return the maximum specified age of the cookie. Ques: 22 What is the use of setComment and getComment methods in Cookies ? Ans: A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

The setComment(java.lang.String purpose) method Specifies a comment that describes a cookie's purpose.The getComment() method returns the comment describing the purpose of the cookie, or null if the cookie has no comment. Ques: 23 When init() and Distroy() will be called. Ans: Both init() and destroy() method called only once within its lifecycle. The init() method will be called after instantaition of servlet, i.e. after the constructor calling. The destroy() method will be called when servlet is removed from the server, i.e. when server shuts down. Ques: 24 What is life cycle of servlet? Ans: A web container manages the life cycle of the servlet : * Loading and Inatantiation: container load the servlet class at the first request to that servlet. The loading of the servlet depends on the attribute <load-onstartup> of web.xml file. Instantiation is done by calling the default constructor. * Initialization: calling the init() method. * Servicing the Request: calling the service() method and pass the HttpServletRequest and HttpServletResponse object as the parameters. * Destroying the Servlet: calling the destroy() method. Ques: 25 What is the difference between an applet and a servlet? Ans: Applets are client side java program that are dynamically downloaded over the internet and executed by browser. Servlets are server side program runs on the server. When a request come to server for the specific servlet, then servlet handles the client request, and send response back to the client. Servlet doesn't have GUI , while applet have GUI. Applet are very heavy to handle as compared to servlet. Ques: 26 What is URL Encoding and URL Decoding ? Ans: Some characters are not valid in URLs like & can't be placed in a URL query string without changing the meaning of that query string. These problems can be be fixed by 'escaping' them. This process involves scanning the text for those characters, and replacing them with a special character-code that browsers can interpret as the correct symbol, without actually using that symbol in your URL. For example, the escaped character code for '=' is '%3d'. Ques: 27 When a session object gets added or removed to the session, which event will get notified ? Ans: When an object is added or removed from a session, the container checks the interfaces implemented by the object. If the object implements the HttpSessionBindingListener, the container calls the matching notification method.

If session is added then sessionCreated() method, and if session is removed then sessionDestroyed() method will be callled automatically by the web container. Ques: 28 How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies? Ans: A cookie has a maximum size of 4K, and no domain can have more than 20 cookies. Ques: 29 How can my application get to know when a HttpSession is removed? Ans: To get notified that a HttpSession is removed or created, you should implement the HttpSessionBindingListener in the class that implements the two of its method : sessionCreated() and sessionDestroyed(). If a session is created or destroyed, the sessionCreated() or sessionDestroyed() method respectively will be called automatically. You must register this listener implementing class inside the <listener>...</listener> element in the deployment descriptor(web.xml) file. Ques: 30 What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically? Ans: Setting the time out programmatically means calling setMaxInactiveInterval(int seconds) from your servlet. Setting the session time out in deployment descriptor means declaratively setting the session timeout. The following setting in the deployment descriptor causes the session timeout to be set to 10 minutes: <session-config> <session-timeout>10</session-timeout> </session-config> Setting the session time out in deployment descriptor allows you to modify the time easily, hard code it into the program requires recompilation overhead. Ques: 31 How to make a context thread safe? Ans: To make the context scope thread safe, you need a lock on context object. To synchronize the context attribute is to synchronize on context object. If a thread gets a lock on context object, then you are guaranteed that only one thread at a time can be getting or setting the context attribute. It only works if all of the other code that manipulate the context attribuet also synchronizes on the servlet context. Ques: 32 What is the difference between an attribute and a parameter? Ans: Request parameters are the name/value pairs, and the result of submitting an HTML form. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using request.getParameter() at the server side. Parameters are Strings, and generally can be retrieved, but not set. Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programatically using setAttribute() method, and retrieve them later using getAttribute() method. Ques: 33 What are the different ways for getting a servlet context? Ans: The different ways for getting a servlet context :

* ServletConfig.getServletContext() * GenericServlet implements ServletConfig, so HttpServlets all have a getServletContext() method * In a Filter you have access to the FilterConfig which is set in the init(FilterConfig fc) callback. You can use FilterConfig.getServletContext(). * In a ServletContextListener or a ServletContextAttributeListener, the event passed to the listener methods has a getServletContext() method. Ques: 34 What is the difference between Context init parameter and Servlet init parameter? Ans: Context init parameter is accessible through out the web application and declared outside the <servlet>...</servlet> element tag in the deployment descriptor(DD) . Servlet init parameters are declared inside the <servlet>...</servlet> element and only accessible only to the that specific servlet. You can access the context init parameters using the getServletContext() method and Servlet init parameters using the getServletConfig() method. Declaring the Servlet init parameter in DD : <servlet> <servlet-name>My Page</servlet-name> <sevlet-class>/mypage</servlet-class> <init-param> <param-name>email</param-name> <param-value>jalees786@gmail.com</param-value) </init-param> </servlet> Declaring the Context init parameter in DD : <context-param> <param-name>webmaster</param-name> <param-value>jalees786@gmail.com</param-value> </context-param> Ques: 35 How will you delete a cookie? Ans: To delete cookie from servlet, get the cookie from the request object and use setMaxAge(0) and then add the cookie to the response object. Cookie killMyCookie = new Cookie("mycookie", null); killMyCookie.setMaxAge(0); response.addCookie(killMyCookie); Ques: 36 How can I set a cookie? Ans: The following program demonstrate that how to set the cookie : import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) { response.addCookie(new Cookie("cookie_name", "cookie_value")); }

public void doGet(HttpServletRequest req, HttpServletResponse res) { doPost(req, res); } } Ques: 37 Why in Servlet 2.4 specification SingleThreadModel has been deprecated? Ans: Tere is no practical implementation to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. Ques: 38 What is HttpTunneling? Ans: Encapsulating the information into the Http header and directed it to a server at the other end of the communication channel that takes the packets, strips the HTTP encapsulation headers and redirects the packet to its final destination. HTTP-Tunnel acts as a socks server, allowing you to use your Internet applications safely despite restrictive firewalls and/or you not be monitored at work, school, goverment and gives you a extra layer of protection against hackers, spyware, ID theft's with our encryption. Reason For HTTP-Tunnel : * Need to bypass any firewall * Need secure internet browsing * Need to use favorite programs with out being monitored by work, school, ISP or gov. * Extra security for online transactions * Encrypt all your Internet traffic. * Need play online games * Visit sites that you are previously blocked * Prevent 3rd party monitoring or regulation of your Internet browsing and downloads * Use your favorite applications previously blocked * Hide your IP address * Make it next to impossible for you to identify online. * Free unlimited data transfer * Compatible with most major Internet applications * Secure and virus-free servers * 99% uptime * No spam, pop-ups, or banners In many cases it is not possible to establish a connection between JMS clients and a SwiftMQ message router or between two SwiftMQ message routers if one part stands behind a firewall. In general it exists a proxy server to which it is allowed exclusively to establish an internet connection by a firewall. To avoid this fact, an operation called HTTP tunneling is used. Ques: 39 What are the differences between a session and a cookie? Ans: Differences between a session and a cookie : * A cookie is a special piece of data with a bit of associated metadata that an HTTP server includes in an HTTP response. A session is a series of related HTTP requests and responses that

together constitute a single conversation between a client and server. * Cookies are stored at the client side whereas session exists at the server side. * A cookie can keep information in the user's browser until deleted, whereas you close your browser you also lose the session. * Cookies are often used to store a session id, binding the session to the user. * There is no way to disable sessions from the client browser but cookies. Ques: 40 What is a output comment? Ans: A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax <!-- comment [ <%= expression %> ] --> Example 1 <!-- This is a commnet sent to client on <%= (new java.util.Date()).toLocaleString() %> -->

Page 3
Ques: 41 Why should we go for inter servlet communication? Ans: Due ot the following reason need inter servlet communication : * Two servlet want to communicate to complete the shopping cart. * One servlet handles the client request and forward it to another servlet to do some calculation or add some information to complete the view. * One servlet want to reuse the some methods of another servlet. Ques: 42 What is the Max amount of information that can be saved in a Session Object ? Ans: There is no limit for amount of information that can be seve into the session object. It depends upon the RAM available on the server machine. The only limit is the Session ID length which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Ques: 43 What is Server side push? Ans: The term 'server push' generally means that a server pushes content to the browser client. Server push is a Netscape-only scheme for providing dynamic web content. Server side push is a mechanism that support real time connection to the server with the advantage of instant updates. Server side push may be emulated in a number of ways. * The client polls the server at a certain interval, say every five minutes. This technique is typically used to update news information. The client does this by reloading a page every so often. * The client uses the 'multipart/x-mixed-replace' content type when sending a response. The content type is expected to send a series of documents one after the other, where each one will replace the previous one. The server might delay

between each part, which gives the illusion that the data is being updated after an interval. This technique requires a connection to stay open. Ques: 44 How can a servlet refresh automatically? Ans: We can Refresh Servlet Page by two ways : one through client side and another through Server Push. Client Side Refresh : < META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet/"> Server Side Refresh : response.setHeader("Refresh",5); This will update the browser after every 5 seconds Ques: 45 What is the difference between ServletContext and ServletConfig? Ans: ServletContext and ServletConfig are declared in the deployment descriptor. ServletConfig is one per servlet and can be accessed only within that specific servlet. ServletContext is one per web application and accessible to all the servlet in the web application. Ques: 46 What are the different ways for session tracking? Ans: The concept of session tracking allows you to maintain the relation between the two successive request from the same client (browser). The browser sends the request to the server and server process the browser request generate the response and send back response to the browser. The server is not at all bothered about who is asking for the pages. The server (because of the use of HTTP as the underlying protocol) has no idea that these 2 successive requests have come from the same user. There is no connection between 2 successive requests on the Internet. There are * Using * Using * Using three ways of tracking sessions : Cookies. URL Rewriting. Hidden Form Fields.

Ques: 47 What mechanisms are used by a Servlet Container to maintain session information? Ans: The mechanisms used by a Servlet Container to maintain session information : a) Cookies b) URL rewriting c) Hidden form fields

d) SSL (using HTTPS protocol) Sessions Ques: 48 What Difference between GET and POST ? Ans: Difference between GET and POST : * Client can send information to the server by two methods : GET and POST. * The GET method appends parameters (name/value) pairs to the URL. The length of a URL is limited, there is a character restriction of 255 in the URL. so this method only works if there are only a few parameters. * The main difference between GET and POST is, POST has a body. Unlike GET, parameters are passed in the body of the POST insteat of appending to the URL. We can send large number of data with the POST. * "GET" is basically for just getting (retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail. * The data send with the GET method is visible at the browser's address bar. Don't send important and sensitive data with GET method, use POST. * Get is idempotent, means it has no side effects on re-requesting the same thing on the server. Ques: 49 What is session? Ans: A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables. A session keeps all of the state that you build up bundled up so that actions you take within your session do not affect any other users connected to other sessions. Ques: 50 What is servlet mapping? Ans: Servlet mapping controls how you access a servlet. Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. For this purpose web container uses the Deployment Decriptor (web.xml) file. Servlets are registered and configured as a part of a Web Application. To register a servlet, you add several entries to the Web Application deployment descriptor. Servlet Mapping : <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>myservlets.MappingExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>com/*</url-pattern> </servlet-mapping> A developer can map all the servelts inside its web application.

Ques: 51 What is servlet context ? Ans: Servlet context defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. A servlet context object is one per web application per JVM and this object is shared by all the servlet. You can get and set the Servlet context object. You can use servelt context object in your program by calling directly getServletContext() or getServletConfig().getServletContext(). Ques: 52 Can we use the constructor, instead of init(), to initialize servlet? Ans: Yes. But you will not get the servlet specific things from constructor. So do not use constructor instead of init(). The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor so you won't have access to a ServletConfig or ServletContext. Plus, all the other servlet programmers are going to expect your init code to be in init(). Ques: 53 What is a servlet ? Ans: Servlets are the server side programs that runs on the server allow developer to add dynamic content and hand it to the web server and web server sent back to the client. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. Typical uses for HTTP Servlets include : * Processing and/or storing data submitted by an HTML form. * Providing dynamic content, e.g. returning the results of a database query to the client. * Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

Question-4: Explain the Servlet Life Cycle. Ans-- Servlet Life Cycle that defines how it is loaded and instantiated, is initialized, handles requests from clients, and is taken out of service, while life cycle in API express by the the init, service, and destroy methods of the javax.servlet.Servlet interface that all servlets must implement directly or indirectly through the GenericServlet or HttpServlet abstract classes. 1. Loaded and Instantiated :- The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is

needed to service a request. when the servlet engine is started, the servlet container loads the servlet class using normal Java class loading facilities. After loading the Servlet class, the container instantiates it for use for client request. 2. Initialization :- After the Instantiated load, the container must be initialized before it can handle request to client. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. Error should be occurs while the servlet is initialized which is: (i). Error Conditions on Initialization :- Whenever a servlet should be initialized, the servlet instance throws an exception which is UnavailableException or ServletException, because the servlet must not be part of active service and must be released by the servlet container. A new instance may be instantiated and initialized by the container after a failed initialization. and remember destroy() method is not called as it is considered unsuccessful initialization. (ii) Tool Considerations:- A servlet should not assumed in an active container runtime until the the init() method of the Servlet interface is called. The triggering of static initialization methods when a tool loads and introspects a Web application is to be distinguished from the calling of the init method 3. Request Handling :- When a servlet is properly initialized, the servlet container may use to handle a client request which is represented by request object ServletRequest. The ServletResponse() method is provide the servlet fill out the response of all the request. While in case of HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse. ** Note some issue occurs by which a servlet container may handle no requests during its lifetime like:(i). Multithreading Issues :- In multithread issue a servlet container may send more than one requests( concurrent request) through the service method to the servlet. (ii) Exceptions During Request Handling :- A ServletException signals that some error occurred during the processing of the request and that the container should take appropriate measures to clean up the request. An UnavailableException signals that the servlet is unable to handle requests either temporarily or permanently. (iii) Thread Safety Issues :- Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread.

Figure-4: Show the Life cycle of the Servlets 4. End of Service :- The servlet container is not required to keep a servlet loaded for any particular period of time. whenever the servlet container determines that a servlet should be removed from service, than it calls the destroy method of the Servlet interface to allow the servlet to release all the resources that is hold and save any persistent state. The destroy method only call, when it must complete execution of any thread that are currently running in the service method of the servlet, or exceed a server-defined time limit.

Ans-- A servlet is an object that extends either the javax.servlet.GenericServlet class or the javax.servlet.http.HttpServlet class. The javax.servlet.GenericServlet class defines methods for building generic, protocol-independent servlets. The javax.servlet.http.HttpServlet class extends this class to provide HTTP-specific methods.

Figure-6: Show the Java Servlets Architecture.

Das könnte Ihnen auch gefallen