Advance Java - Unit2
Advance Java - Unit2
UNIT 2
By Shivani Deopa
Servlets:
Introduction
• Today we all are aware of the need to create dynamic web pages i.e. the ones
that can change the site contents according to the time or can generate the
content according to the request received by the client. If you like coding in Java,
then you will be happy to know that using Java there also exists a way to generate
dynamic web pages and that way is Java Servlet.
• Servlets are the Java programs that runs on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, then send response back to
the web server.
Properties of Servlets :
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from web server.
Execution of Servlets involves six basic steps:
• The clients send the request to the web server.
• The web server receives the request.
• The web server passes the request to the corresponding servlet.
• The servlet processes the request and generates the response in the
form of output.
• The servlet sends the response back to the web server.
• The web server sends the response back to the client and the client
browser displays it on the screen.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
GET POST
1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data data can be sent because data is sent in
is sent in header. body.
2) Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
• destroy() method: The destroy() method runs only once during the lifetime of a Servlet
and signals the end of the Servlet instance.
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.
• service() method: The service() method of the Servlet is invoked to inform the Servlet
about the client requests.
• This method uses ServletRequest object to collect the data requested by the client.
• This method uses ServletResponse object to generate the output content.
// service() method
public class MyServlet implements Servlet{
public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
import java.io.*; public void doGet(HttpServletRequest
import javax.servlet.*; req, HttpServletResponse resp)
import javax.servlet.http.*; throws ServletException,
IOException
public class AdvanceJavaConcepts {
extends HttpServlet
{ resp.setContentType("text/html");
private String output; PrintWriter out = resp.getWriter();
public void init() throws out.println(output);
ServletException }
{ public void destroy()
output = "Advance Java Concepts"; {
} System.out.println("Over");
}
}
ServletConfig
• ServletConfig interface is used to assign properties to a Servlet at the time of Servlet
object creation itself (known as Servlet Initialization Parameters) by the
container; exactly the way you use constructor in case of applications.
• web.xml is known as deployment descriptor, where in, the deployment particulars (that
also include initialization parameters) of a Servlet are written by the Programmer. The
particulars are declared in <init-param> tag in web.xml file. To read this, <init-param>
tag data, ServletConfig interface is used.
• Infact, an object of ServletConfig is created by the Container itself at the time it creates a
Servlet object. For every object of Servlet, the container creates, also an object of
ServletConfig. This ServletConfig object is used to communicate with the Servlet under
execution. Eventhough, the contianer creates the ServletConfig object implicitly for its
purpose, the Programmer can make use of the object in his code to read initialization
parameters into the Servlet from web.xml file.
• If the parameter values change, the web.xml file need not be compiled. At the time
reading, whatever values exists in the web.xml file, with those values or parameters only
the Servlet is initialized.
• For each Servlet under execution, a ServletConfig object is created by the Servlet
container and is used by the Programmer to read the Servlet specific data declared
(written) in web.xml in the form of tags.
• ServletConfig is an interface from javax.servlet package.
• The getServletConfig() method of GenericServlet returns an object of ServletConfig.
• The ServletConfig object created by the Web container for a specific Servlet cannot read
other servlet’s init-param data.
• ServletConfig object is specific for a Servlet. Other way to say, if 100 servlet objects are
being executed in the container, 100 ServletConfig objects are also created implicitly
used by the container to communicate with the Servlet.
• When the container destroys the Servlet object, along with it its
corresponding ServletConfig object also destroyed.
• Programmer can make use ServletConfig object to read tags of the Servlet.
• <init-param> tag data is known as initialization parameters and are used to initialize the
Servlet with some special properties.
• The method of ServletConfig object used to read is "String getInitParameter(String)".
• The data, to be read by ServletConfig, is written within <servlet> tag.
SR.NO. METHOD SUMAMRY
Returns a String containing the value of the
1 String getInitParameter(String name) named initialization parameter, or null if the
parameter does not exist.
• Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
• Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
• Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
• Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
• javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.
• Other methods required for using Cookies
• For adding cookie or getting the value from the cookie, we need some
methods provided by other interfaces.
• They are:
1. public void addCookie(Cookie ck): method of HttpServletResponse
interface is used to add cookie in response object.
2. public Cookie[] getCookies(): method of HttpServletRequest
interface is used to return all the cookies from the browser.
How to create Cookie?
• Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Cookie(String name, String value) constructs a cookie with a specified name and value.
• There are given some commonly used methods of the Cookie class.
Hidden Form Field
• In case of Hidden Form Field, a hidden (invisible) text field is used for
maintaining the state of a user.
• In such case, we store the information in the hidden field and get it
from another servlet. This approach is better if we have to submit
form in all the pages and we don't want to depend on the browser.
• Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vimal Jaiswal">
• Here, uname is the hidden field name and Vimal Jaiswal is the hidden
field value.
Real application of hidden form field
• It is widely used in comment form of a website. In such case, we store
page id or page name in the hidden field so that each page can be
uniquely identified.
• Disadvantage
1. Difficult to debug for errors.
2. First time access leads to wastage of time
3. It’s output is HTML which lacks features.
JSP Life Cycle
• A Java Server Page life cycle is defined as the process started with its
creation which later translated to a servlet and afterward servlet lifecycle
comes into play. This is how the process goes on until its destruction.
• Following steps are involved in JSP life cycle:
1. Translation of JSP page to Servlet
2. Compilation of JSP page(Compilation of JSP into test.java)
3. Classloading (test.java to test.class)
4. Instantiation(Object of the generated Servlet is created)
5. Initialization(jspInit() method is invoked by the container)
6. Request processing(_jspService()is invoked by the container)
7. JSP Cleanup (jspDestroy() method is invoked by the container)
• Translation of JSP page to Servlet :
This is the first step of JSP life cycle. This translation phase deals with Syntactic
correctness of JSP. Here test.jsp file is transllated to test.java.
• Compilation of JSP page :
Here the generated java servlet file (test.java) is compiled to a class file (test.class).
• Classloading :
Servlet class which has been loaded from JSP source is now loaded into container.
• Instantiation :
Here instance of the class is generated. The container manages one or more instance by
providing response to requests.
• Initialization :
jspInit() method is called only once during the life cycle immediately after the generation
of Servlet instance from JSP.
• Request processing :
_jspService() method is used to serve the
raised requests by JSP.It takes request and
response object as parameters.This method
cannot be overridden.
• JSP Cleanup :
In order to remove the JSP from use by the
container or to destroy method for servlets
jspDestroy()method is used. This method is
called once, if you need to perform any
cleanup task like closing open files, releasing
database connections jspDestroy() can be
overridden.
JSP Scope Object
• The availability of a JSP object for use from a particular place of the
application is defined as the scope of that JSP object. Every object
created in a JSP page will have a scope. Object scope in JSP is
segregated into four parts and they are page, request, session and
application.
• page
‘page’ scope means, the JSP object can be accessed only from within
the same page where it was created. The default scope for JSP objects
created using <jsp:useBean> tag is page. JSP implicit objects out,
exception, response, pageContext, config and page have ‘page’ scope.
• request
A JSP object created using the ‘request’ scope can be accessed from any
pages that serves that request. More than one page can serve a single
request. The JSP object will be bound to the request object. Implicit object
request has the ‘request’ scope.
• session
‘session’ scope means, the JSP object is accessible from pages that belong
to the same session from where it was created. The JSP object that is
created using the session scope is bound to the session object. Implicit
object session has the ‘session’ scope.
• application
A JSP object created using the ‘application’ scope can be accessed from any
pages across the application. The JSP object is bound to the application
object. Implicit object application has the ‘application’ scope.
JSP Implicit Object
• These Objects are the Java objects that the JSP Container makes available
to the developers in each page and the developer can call them directly
without being explicitly declared. JSP Implicit Objects are also called pre-
defined variables.
• Following table lists out the nine Implicit Objects that JSP supports −
1. Request 2. Response
3. Out 4. Session
5. Application 6. Config
7. pageContext 8. Page
9. Exception
• The request Object
1. The request object is an instance of
a javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent that
request.
2. The request object provides methods to get the HTTP header
information including form data, cookies, HTTP methods etc.
out.print(dataType dt)
1
Print a data type value
out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.
out.flush()
3
Flush the stream.
• The session Object
1. The session object is an instance of javax.servlet.http.HttpSession and
behaves exactly the same way that session objects behave under Java
Servlets.
2. The session object is used to track client session between client requests
• The code placed within JSP expression tag is written to the output stream
of the response. So you need not write out.print() to write data. It is mainly
used to print the values of variable or method.
• Syntax of JSP expression tag
<%= statement %>