0% found this document useful (0 votes)
115 views

Kaveri College of Arts, Science and Commerce: Tybsc (CS) Java Servlet

This document provides information about Java servlets including: - Java servlets run on web servers and handle HTTP requests and responses, extending the functionality of servers like web servers. - The document discusses the servlet lifecycle, types of servlets including generic and HTTP servlets, and provides examples of basic servlets handling GET and POST requests. - Session tracking mechanisms for maintaining state across requests are examined, including cookies, URL rewriting, and hidden form fields. The document also discusses how HTTP sessions in servlets provide a higher-level API for session tracking.

Uploaded by

Pallavijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Kaveri College of Arts, Science and Commerce: Tybsc (CS) Java Servlet

This document provides information about Java servlets including: - Java servlets run on web servers and handle HTTP requests and responses, extending the functionality of servers like web servers. - The document discusses the servlet lifecycle, types of servlets including generic and HTTP servlets, and provides examples of basic servlets handling GET and POST requests. - Session tracking mechanisms for maintaining state across requests are examined, including cookies, URL rewriting, and hidden form fields. The document also discusses how HTTP sessions in servlets provide a higher-level API for session tracking.

Uploaded by

Pallavijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

KAVERI COLLEGE OF ARTS,

SCIENCE AND COMMERCE


TYBSC(CS)
JAVA SERVLET
APPLETS
 JApplet is like a JFrame JApplet
 Already has a panel
• Access panel with JApplet.getContentPane( )

import javax.swing.*; contentPane

class hello extends JApplet {


public void init(){
JButton b = new JButton(“press me”); JButton
getContentPane().add(b);
}
}
HTTP SERVLET OVERVIEW
Servlets are modules that extend request/response-oriented servers, such as
Java-enabled web servers. For example, a servlet might be responsible for
taking data in an HTML order-entry form and applying the business logic used
to update a company's order database.
JAVA SERVLETS
 Java’s answer to CGI + ASP
 A little more general than CGI/ASP, etc.
 Work with all major web servers
 Need web server servlet engine
 Need servlet development kit
WHAT'S GOOD ABOUT THEM?
 Concurrency – A servlet can handle multiple request
(Synchronize)
 Forward Request
 Portability
 Efficiency
 Power
 Safety
TYPES OF SERVLET
 Generic Servlet
 javax.servlet (package)
 extends javax.servlet.Servlet
 service method
 Http Servlet
 javax.servlet.http (package)
 extends javax.servlet.HttpServlet
 doget(), doPost()….
TYPES OF SERVLETS (CONT..)
Generic servlet
service(Request, Response) throws
ServletException, IOException
HttpServlet
doGet(HttpServletRequest req,
HttpServletResponse res)
BASIC SERVLET EXAMPLE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Test extends HttpServlet{


public void doGet(HttpServletRequest in,
HttpServletResponse out) throws ServletException,
IOException {
out.setContentType(“text/html”);
PrintWriter p = res.getWriter();
p.println(“<H1>HELLO, WORLD!</H1>”);
}
}
POST EXAMPLE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Test extends HttpServlet{


public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String pin = req.getParameter(“to”);
String orig = req.getParameter(“from”);
out.println(“Sending page to “ + pin + “ from “ +
orig);
// Actually send the page.
}
public void doPost(HttpServletRequest in,
HttpServletResponse out) throws ServletException,
IOException {
doGet(in, out);
}
}
COUNTER EXAMPLE
import ….;
public class SimpleCounter extends HttpServlet {
int count =0 ;
public void doGet( …….) throws ….
{
res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
count ++;
out.println(“Hit number: “+count);
}
}// end of class
 What is the problem with the above example??
SYNCHONIZED COUNTER
import ….;
public class SimpleCounter extends HttpServlet {
int count =0 ;
public void doGet( …….) throws ….
{
res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
synchonize(this) {
count ++;
out.println(“Hit number: “+count);
}
}
}// end of class
SERVLET LIFE CYCLE
 Initialize using init method
 Servlet handles requests/clients
 Server removes the servlet using destroy method
SERVLETS VS. APPLETS
 Similarities
 Neither has a main()
 Both have init() and destroy()
 Both are part of a larger application made for the web
SERVLETS VS. APPLETS (CONT..)
 Dissimilarity
 Applets run on the client (browser) while servlets run on the
HTTP server
 Applets are usually “crippled” in functionality, having limited
ability to look at the local file system, establish network
connections, etc.
 Servlets are generally built to handle multiple clients at once,
whereas applets generally service one client at a time.
 Servlets handle HTTP request
…
SERVLET LIFE CYCLE
 Servlet life cycle
 Create
 Initialize
 Service
 Destroy
 When HTTP calls for a servlet
 Not loaded: Load, Create, Init, Service
 Already loaded: Service
SESSION TRACKING
 Many applications need to maintain state across a series
of requests from the same user (or originating from the
same browser), e.g.,
 When clients at an on-line store add an item to their shopping
cart, how does the server know what’s already in the cart
 When clients decide to proceed to checkout, how can the
server determine which previously created shopping cart is
theirs?
 HTTP is a stateless protocol
 Each time, a client talks to a web server, it opens a new
connection
 Server does not automatically maintains “conversational
state” of a user
SESSION TRACKING MECHANISMS
 Three mechanisms of session tracking
 Cookies
 URL rewriting
 Hidden form fields
WHAT IS COOKIE
 Cookie is a small amount of information sent by a servlet to a
web browser
 Saved by the browser, and later sent back to the server in
subsequent requests
 A cookie has a name, a single value, and optional attributes (name/value
pair)
 A cookie’s value can uniquely identify a client
 Server uses cookie’s value to extract information about the
session from some location on the server
COOKIE SERVLET
public class CookieTest extends javax.servlet.http.HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException {
OutputStream out = res.getOutputStream();
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
Cookie[] cookies = req.getCookies(); Cookie current = null;
if(cookies != null) {
for (int i=0;i<cookies.length;i++) {
pw.println("name="+cookies[i].getName());
pw.println("value="+cookies[i].getValue());
pw.println("version="+cookies[i].getVersion());
if(cookies[i].getName().equals("cookie")) { current=cookies[i]; }
pw.println();
} }
int count=0;
if(current != null) {
count = Integer.parseInt(current.getValue());
res.addCookie(new Cookie("previouscookie",new integer(count).toString()));
pw.println("Value stored in cookie = "+count);
}
res.addCookie(new Cookie("cookie",new Integer(++count).toString()));
pw.flush(); pw.close();
} }
COOKIES AS SESSION TRACKING MECHANISM
 Advantage
 Very easy to implement
 Highly customable
 Persist across browser shut-downs
 Disadvantage
 Users may turn off cookies from privacy or security reason
 Not quite universal browser support
URL REWRITING
 URLs can be rewritten or encoded to include session
information
 URL rewriting usually includes a session ID
 Session ID can be sent as an added parameters:
 http://.../servlet /Rewritten?sessionid=678
URL REWRITING AS SESSION TRACKING
 Advantages
 Users remain anonymous
 There are universally supported
 Disadvantages
 Tedious to rewrite all URLs
 Only works for dynamically created documents
HIDDEN FORM FIELDS
 Hidden form fields do not display in the browser, but can be sent
back to the server by submit
<INPUT TYPE=“HIDDEN” Name=“session” Value =‘…’>
 Fields can have identification (session id) or just something to
remember
 Servlet reads the fields using request.getParameter()
HIDDEN FORM FIELDS AS SESSION TRACKING
Advantages
Universally supported
Allow anonymous users
Disadvantages
Only works for a sequence of dynamically generated
forms
Breaks down with static documents, emailed
documents, bookmarked documents
Cannot support browser shutdown
STEPS OF DOING SESSION TRACKING
 Programmers have to do the following steps in order to
use the aforementioned tracking mechanisms:
 Generating and maintaining a session id for each session
 Passing session id to client via either cookie or URL
 Extracting session id information either from cookie or URL
 Creating and maintaining a hashtable in which session id and session
information are stored
 Coming up with a scheme in which session information can be added or
removed
 These mechanisms can pass “session id”, but
 do not provide high-level programming APIs
 do not provide a framework from managing sessions
“SESSION TRACKING” FEATURES OF SERVLET

 Provides higher-level API for session tracking


 Built on top of cookie or URL rewriting
 Servlet container maintains
 Internal hashtable of session ids
 Session information in the form of HttpSession
 Provides a simple API for adding and removing session information
(attributes) to HttpSession
 Could automatically switch to URL rewriting if cookies are unsupported
or explicitly disabled
HTTPSESSION
 To get a user’s existing or new session object:
 HttpSession session = request.getSession(true)
• flag = true to create a new session if none exists
 HttpSession is java interface containing methods to
• View and manipulate information about a session, such as the session identifier, creation time,
and last accessed time
• Bind objects to sessions, allowing user information to persist across multiple user connections
 To Store and retrieve of attribute
 session.setAttribute(“cartItem”, cart)
 session.getAttribute(“cartItem”)
 All session data are kept on the server
 Only session ID sent to client
SAMPLE HTTP SESSION
public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setContentType("text/html");
OutputStream out = res.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
HttpSession session = req.getSession(false);
if (session == null) {
session=req.getSession(true);
session.putValue ("VisitCount", "1");
}
pw.println("<html><body><pre>");
pw.println("session.isNew()="+session.isNew());
pw.println("session.getCreationTime()="+ new java.util.Date( session.getCreationTime()));
pw.println("session.getID()="+session.getId());
pw.println("session.getLastAccessedTime()=" + new
java.util.Date(session.getLastAccessedTime()));
String strCount = (String) session.getValue("VisitCount");
pw.println("No. of times visited = " + strCount);
int count = Integer.parseInt(strCount); count++;
session.putValue("VisitCount", Integer.toString(count));
pw.println ("</pre></body></html>");
pw.flush();
}
}
SESSION TIMEOUT
 Used when an end-user can leave the browser without
actively closing a session
 Session usually timeout after 30 minutes of inactivity
 Product specific
 A different timeout may be set
• getMaxInactiveInterval()
• setMaxInactiveInterval()
ISSUES WITH “STALE” SESSION OBJECTS

The number of “stale” session objects that are in


“to be timed out” could be large and affect system
performance, for example,
1000 users with average 2 minutes session time, thus
15000 usrs during a period of 30 minutes
4K bytes of data per session
15000 sessions * 4K = 60M bytes of session data –
just for one application
SESSION INVALIDATION
 Can be used by servlet programmer to end a session proactively
by calling invalidate()
 When a user at the browser clicks on “logout” button
 When business logic ends a session
 Caution: a session object could be shared by multiple servlet/JSP-
pages and invalidating it could destroy data that other
servlet/JSP-pages are using
HTTPSESSION METHODS
 Object getAttribute(String) – Value for the given name
 Enumeration getAttributeNames() - All the names of all attributes in the session
 long getCreationTime() - Time at which this session was created
 String getId() - Identifier assigned to this session
 long getLastAccessedTime() - Last time the client sent a request carrying the identifier
assigned to the session
 int getMaxInactiveInterval() - Max time (in seconds) between between requests that the
session will be kept
 ServletContext getServletContext() - ServletContext for session
 void invalidate() - Invalidates the session
 boolean isNew() - true if it has been created by the server (client has not yet acknowledged
joining the session)
 void setAttribute(String, Object) - Sets the value for the given name
 void removeAttribute(String) - Removes the value for the given name
 void setMaxInactiveInterval(int) - Sets the maximum interval between requests

You might also like