0% found this document useful (0 votes)
14 views20 pages

Unit Iii Server Side Programming

Unit III focuses on server-side programming with Java Servlets, which act as intermediaries between web clients and server applications. It covers servlet architecture, lifecycle methods (init, service, destroy), and session tracking techniques such as cookies, hidden form fields, URL rewriting, and HttpSession. The document also provides examples of servlet implementation and the Servlet API structure.

Uploaded by

princy_usha
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)
14 views20 pages

Unit Iii Server Side Programming

Unit III focuses on server-side programming with Java Servlets, which act as intermediaries between web clients and server applications. It covers servlet architecture, lifecycle methods (init, service, destroy), and session tracking techniques such as cookies, hidden form fields, URL rewriting, and HttpSession. The document also provides examples of servlet implementation and the Servlet API structure.

Uploaded by

princy_usha
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/ 20

[Type the document title]

UNIT III SERVER SIDE PROGRAMMING


Servlets
 Java Servlets are java programs that run on a Web or
Application server.
 Servlets are act as a middle layer between a requests
coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
 Using Servlets, you can collect input from users
through web page forms, present records from a database
or another source, and create web pages dynamically.
 Java Servlets often serve the same purpose as
programs implemented using the Common Gateway
Interface (CGI).
Servlets offer several advantages in comparison with
the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web
server. It is not necessary to create a separate process to
handle each client request.
 Servlets are platform-independent because they are
written in Java.
 Java security manager on the server enforces a set of
restrictions to protect the resources on a server machine.
So servlets are trusted.
 The full functionality of the Java class libraries is
available to a servlet. It can communicate with applets,

[Type text] Page 3.1


[Type the document title]

databases, or other software via the sockets and RMI


mechanisms that you have seen already.
Servlets Architecture
The following diagram shows the position of Servlets in a
Web Application.

 Servlets perform the following major tasks –


 When a client make a request for some servlet, they
actually uses the Web Browser in which request is written
as a URL.
 The web browsers then send this request to web
server. The web server first finds the requested servlet.
 The servlet gathers the relevant information in order
to satisfy the client’s request and Builds a web page.
 The web page is then displayed to the client.
Servlet Life Cycle
There are important methods in the life cycle of servlets.
A servlet life cycle can be defined as the entire process from its
creation till the destruction.
 The servlet is initialized by calling the init() method.

[Type text] Page 3.2


[Type the document title]

 The servlet calls service() method to process a


client's request.
 The servlet is terminated by calling
the destroy() method.
 Finally, servlet is garbage collected by the garbage
collector of the JVM.
The init() Method
 The init method is called only once. It is called only
when the servlet is created. It is used for one-time
initializations.
 The servlet is normally created when a user first
invokes a URL corresponding to the servlet. But you can
also specify that the servlet be loaded when the server is
first started.
 The init() method simply creates or loads some data
that will be used throughout the life of the servlet.
The init method definition is

public void init() throws ServletException {


// Initialization code...
}

The service() Method


 The service() method is the main method to perform
the actual task.
 The servlet container (i.e. web server) calls the
service() method to handle requests coming from the
client( browsers) and to write the formatted response

[Type text] Page 3.3


[Type the document title]

back to the client.


 Each time the server receives a request for a servlet,
the server spawns a new thread and calls service.
 The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.
The syntax of this method −

public void service(ServletRequest request, ServletResponse


response)
throws ServletException, IOException {
}

The doGet() Method


A GET request results from a normal request for a URL or from
an HTML form that has no METHOD specified and it should be
handled by doGet() method.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically
lists POST as the METHOD and it should be handled by
doPost() method.

public void doPost(HttpServletRequest request,

[Type text] Page 3.4


[Type the document title]

HttpServletResponse response)throws ServletException,


IOException {
// Servlet code
}

The destroy() Method


 The destroy() method is called only once at the end of
the life cycle of a servlet.
 This method gives your servlet a chance to close
database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such
cleanup activities.
 After the destroy() method is called, the servlet object
is marked for garbage collection.
 The destroy method definition is

public void destroy() {


// Finalization code...
}

Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LifeCycle extends GenericServlet {
public void init(ServletConfig config)throws ServletException
{
System.out.println(“init”);

[Type text] Page 3.5


[Type the document title]

}
public void service(ServletRequest req, ServletResponse res)
throws
ServletException, IOException
{
System.out.println(“from service”);
printWriter out=response.getWriter();
out.println(“Hello. How r u?”);
out.print(“Welcome”);
}
public void destroy() {
System.out.println(“destroy”);
}
}
Servlet API:
 Servelt API contains three packages
 javax.servlet: Package contains a number of classes and
interfaces that describe the contract between a servlet class
and the runtime environment provided for an instance of such
a class a
conforming servelt container.
 javax.servlet.aanotation: Package contains a number of
annotations that allow users to use annotations to declare
servlets , filters, listeners and specify the metadata for the
declared component
 javax.servlet.http: Package contains a number of classes

[Type text] Page 3.6


[Type the document title]

and interfaces that describe and define the contract between a


servlet class running under the HTTP protocol and the runtime
environment provided for an instance of such class by a
confirming servlet container.
Session Tracking in Servlets
 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.
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

[Type text] Page 3.7


[Type the document title]

age, and a version number.

How Cookie works


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.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletRe
sponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object

[Type text] Page 3.8


[Type the document title]

response.addCookie(ck);//adding cookie in the response


//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}

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

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResp


onse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

[Type text] Page 3.9


[Type the document title]

out.close();

}catch(Exception e){System.out.println(e);}
}

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>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

[Type text] Page 3.10


[Type the document title]

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

2) 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.
<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.

[Type text] Page 3.11


[Type the document title]

2. Extra form submission is required on each pages.


3. Only textual information can be used.
EXAMPLE
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletRespo
nse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//creating form that have invisible textfield


out.print("<form action='servlet2'>");

[Type text] Page 3.12


[Type the document title]

out.print("<input type='hidden' name='uname' value='"+n+"


'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletRes
ponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();

[Type text] Page 3.13


[Type the document title]

}catch(Exception e){System.out.println(e);}
}
}
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>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

[Type text] Page 3.14


[Type the document title]

</web-app>

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.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

[Type text] Page 3.15


[Type the document title]

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletRes


ponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}

}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

[Type text] Page 3.16


[Type the document title]

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletRes


ponse response) {
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

//getting value from the query string


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}

}
web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>

[Type text] Page 3.17


[Type the document title]

<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
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.

[Type text] Page 3.18


[Type the document title]

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletRes


ponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='servlet2'>visit</a>");

[Type text] Page 3.19


[Type the document title]

[Type text] Page 3.20

You might also like