0% found this document useful (0 votes)
10 views24 pages

java web UNIT 2 servlets

Servlet technology enables the creation of dynamic web applications on the server side, offering advantages over CGI scripting. The servlet life cycle consists of loading the servlet class, creating an instance, invoking the init method, processing requests via the service method, and finally invoking the destroy method. Session tracking techniques, such as cookies and URL rewriting, are used to maintain user state in the stateless HTTP protocol.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views24 pages

java web UNIT 2 servlets

Servlet technology enables the creation of dynamic web applications on the server side, offering advantages over CGI scripting. The servlet life cycle consists of loading the servlet class, creating an instance, invoking the init method, processing requests via the service method, and finally invoking the destroy method. Session tracking techniques, such as cookies and URL rewriting, are used to maintain user state in the stateless HTTP protocol.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT-II

INTRODUCTION TO SERVLETS

Servlet technology is used to create a web application (resides at server


side and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before


Servlet, CGI (Common Gateway Interface) scripting language was common
as a server-side programming language. However, there were many
disadvantages to this technology. We have discussed these disadvantages
below.

There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

Servlet can be described in many ways, depending on the context.


o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any
Servlet.
o Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page.
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the
life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready
state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web
container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.
Play Videox

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init me
life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps
as described above then calls the service method. If servlet is initialized, it
calls the service method. Notice that servlet is initialized only once. The
syntax of the service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any
resource for example memory, thread etc. The syntax of the destroy method
of the Servlet interface is given below:

1. public void destroy()

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass
HTTP request information to the external program to process the request.
For each request, it starts a new process.

Disadvantages of CGI
There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the
response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.

HTTP Requests
The request sent by the computer to a web server, contains all sorts of
potentially interesting information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request
message which includes following information:

o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header

The HTTP request method indicates the method to be performed on the


resource identified by the Requested URI (Uniform Resource Identifier).
This method is case-sensitive and should be used in uppercase.

The HTTP request methods are:


HTTP Description
Request

GET Asks to get the resource at the requested URL.

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.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request
URL can respond

Session Tracking in Servlets


1. Session Tracking
2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also


known as session management in servlet.

Http protocol is a stateless so we need to maintain state using session


tracking techniques. Each time user requests to the server, server treats the
request as the new request. So we need to maintain the state of an user to
recognize to particular user.
HTTP is stateless that means each request is considered as the new request.
It is shown in the figure given below:

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the
multiple client requests.

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.

By default, each request is considered as a new request. In cookies technique, we


add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

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.
index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29.}

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22.}

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10.<url-pattern>/servlet1</url-pattern>
11.</servlet-mapping>
12.
13.<servlet>
14.<servlet-name>s2</servlet-name>
15.<servlet-class>SecondServlet</servlet-class>
16.</servlet>
17.
18.<servlet-mapping>
19.<servlet-name>s2</servlet-name>
20.<url-pattern>/servlet2</url-pattern>
21.</servlet-mapping>
22.
23.</web-app>
Output
2) Hidden Form Field
1. Hidden Form Field
2. Example of Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for


maintaining the state of an 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.

1. <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.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.
3. Only textual information can be used.

Example of using Hidden Form Field


In this example, we are storing the name of the user in a hidden textfield and
getting that value from another servlet.

3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next
Servlet or the next resource. We can send parameter name/value pairs using
the following format:

url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use
getParameter() method to obtain a parameter value.

Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.

4) HttpSession interface
In such case, container creates a session id for each user.The container uses
this id to identify the particular user.An object of HttpSession can be used to
perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of
HttpSession:

1. public HttpSession getSession():Returns the current session associated


with this request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current session and
create is true, returns a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier


value.
2. public long getCreationTime():Returns the time when this session was
created, measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a
request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects
bound to it.

Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from
one of the following scopes:

1. request scope
2. session scope
3. application scope

The servlet programmer can pass informations from one servlet to another
using attributes. It is just like passing object from one class to another so
that we can reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and


ServletContext interface
There are following 4 attribute specific methods. They are as follows:
1. public void setAttribute(String name,Object object):sets the
given object in the application scope.
2. public Object getAttribute(String name):Returns the attribute for
the specified name.
3. public Enumeration getInitParameterNames():Returns the names
of the context's initialization parameters as an Enumeration of String
objects.
4. public void removeAttribute(String name):Removes the attribute
with the given name from the servlet context.

DemoServlet1.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet1 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10.PrintWriter out=res.getWriter();
11.
12.ServletContext context=getServletContext();
13.context.setAttribute("company","IBM");
14.
15.out.println("Welcome to first servlet");
16.out.println("<a href='servlet2'>visit</a>");
17.out.close();
18.
19.}catch(Exception e){out.println(e);}
20.
21.}}

DemoServlet2.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet2 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10.PrintWriter out=res.getWriter();
11.
12.ServletContext context=getServletContext();
13.String n=(String)context.getAttribute("company");
14.
15.out.println("Welcome to "+n);
16.out.close();
17.
18.}catch(Exception e){out.println(e);}
19.}}

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>DemoServlet1</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10.<servlet>
11.<servlet-name>s2</servlet-name>
12.<servlet-class>DemoServlet2</servlet-class>
13.</servlet>
14.<servlet-mapping>
15.<servlet-name>s2</servlet-name>
16.<url-pattern>/servlet2</url-pattern>
17.</servlet-mapping>
18.</web-app>

SingleThreadModel interface
The servlet programmer should implement SingleThreadModel interface to
ensure that servlet can handle only one request at a time. It is a marker
interface, means have no methods

This interface is currently deprecated since Servlet API 2.4 because it doesn't
solves all the thread-safety issues such as static variable and session
attributes can be accessed by multiple threads at the same time even if we
have implemented the SingleThreadModel interface. So it is recommended to
use other means to resolve these thread safety issues such as synchronized
block etc.
Example of SingleThreadModel interface

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.SingleThreadModel;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class MyServlet extends HttpServlet implements SingleThreadMod
el{
9. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
10. throws ServletException, IOException {
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13. out.print("welcome");
14. try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}

15. out.print(" to servlet");


16. out.close();
17. }
18. }

ServletOutputStream class
ServletOutputStream class provides a stream to write binary data into the
response. It is an abstract class.

The getOutputStream() method of ServletResponse interface returns the


instance of ServletOutputStream class. It may be get as:

1. ServletOutputStream out=response.getOutputStream();
Methods of ServletOutputStream class
The ServletOutputStream class provides print() and println() methods that
are overloaded.

1. void print(boolean b){}


2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}
9. void println(boolean b){}
10. void println(char c){}
11. void println(int i){}
12. void println(long l){}
13. void println(float f){}
14. void println(double d){}
15. void println(String s){}

Example

1. package com.javatpoint;
2. import java.io.*;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class DisplayImage extends HttpServlet {
6. public void doGet(HttpServletRequest request,HttpServletResponse resp
onse)
7. throws IOException
8. {
9. response.setContentType("image/jpeg");
10. ServletOutputStream out;
11. out = response.getOutputStream();
12. FileInputStream fin = new FileInputStream("c:\\test\\java.jpg");
13. BufferedInputStream bin = new BufferedInputStream(fin);
14. BufferedOutputStream bout = new BufferedOutputStream(out);
15. int ch =0; ;
16. while((ch=bin.read())!=-1)
17. {
18. bout.write(ch);
19. }
20. bin.close();
21. fin.close();
22. bout.close();
23. out.close();
24. }
25. }

You might also like