Publishing Data on the Internet Client 1 DB Internet Client 2 Client n.

Post on 26-Dec-2015

228 views 4 download

Tags:

Transcript of Publishing Data on the Internet Client 1 DB Internet Client 2 Client n.

Publishing Data on the Internet

Client 1

DB

Internet

Client 2

Client n

Web Computing: Servlets

CS587x LectureDepartment of Computer Science

Iowa State University

What to coverIntroduction on servlet Servlet architecture Servlet programming and example

Session management Cookie URL rewriting Hidden form field HttpSession

What is a ServletA servlet can be thought of as a server-side applet Applet: a java program that runs

within the web browser Servlet: a java program that runs

within the web server Servlets are loaded and executed by

a web server in the same manner that applets are loaded and executed by a web browser

Servlet Architecture

The client makes a request via HTTPThe web server receives the requests and forwards it to the servlet

If the servlet has not yet been loaded, the web server loads it into the JVM and executes it

The servlet receives the HTTP request and performs some type of processThe servlet returns a response to the web serverThe web server forwards the response to the client

Client (web browser)

WebServer

HTTP request

HTTP response

ServletContainer Servlet

Why Use Servlets

Servlets are designed to replace CGI scripts Platform-independent and extensible

CGI scripts are typically written in Perl or C, and are very much tied to a particular server platform

Servlet is written in Java, which can easily integrate with existing legacy systems through RMI, CORBA, and/or JNI

Persistent and fast Servers are loaded only once by the web server and

can maintain services between requests (particularly important for maintaining database connections)

CGI scripts are transient – a CGI script is removed from memory after it is complete

For each browser request, the web server must spawn a new operating system process

Secure The only way to invoke a servlet from the outside

world is through a web server, which can be protected behind a firewall

What can you build with servlets

Search enginesE-commerce applicationsShopping cartsProduct catalogsPersonalization systemsIntranet application Groupware applications: bulletin boards, file sharing, etc.

Steps of Servlet Processing1. Read any data sent by the server

Capture data submitted by an HTML form

2. Look up any HTTP information Determine the browser version, host name of client,

cookies, etc.

3. Generate the results Connect to databases, connect to legacy

applications, etc.

4. Format the results Generate HTML on the fly

5. Set the appropriate HTTP headers Tell the browser the type of document being

returned or set any cookies

6. Send the document back to the client

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

How to program servletsServlets rely on classes defined in the javax.servlet and javax.servlet.http packages

The two packages are standard extension to Java API

A user servlet implements the servlet interface, which provides

the basic structure methods for servlets, such as initializing, service, and destruction methods

The methods for accessing context & configuration

HTTPServlet class Starting point for new web servlets Extend the class & override desired methods:

doGet, doPost, doPut, doDelete, doTrace, and doOptions Called by the HTTPServlet's service method based on HTTP request Each returns HTTP_BAD_REQUEST error response

Get & Post SimilaritiesGET and POST methods look the same to servletsCan override doGet and doPost like this to perform common operations:

public void doGet(HttpServletRequest req, HttpServletResponse res) {

doGetPost(req, res); }

public void doPut(HttpServletRequest req, HttpServletResponse res) {

doGetPost(req, res); }

public void doGetPut(HttpServletRequest req, HttpServletResponse res) {

// Implement the common code here}

Simple Servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends javax.servlet.http.HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException

{ res.setContentType("text/html"); OutputStream out = res.getOutputStream(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); pw.println ("<CENTER><H3> Hello World </H3></CENTER>"); pw.flush(); pw.close(); }}

Running Servlets

Jakarta/Apache Tomcat Supercedes Java Apache and JServ

Macromedia JRunServletExecWeblogicBorland Enterprise Application Server/JBuilderJava Servlet Development Kit (JSDK)

Single Threaded ExampleBy default, uses shared threads

Single instance of servlet shared by all requests One thread created for each request Class & instance variables are thread-unsafe; auto variables are

thread-safeIn some applications, you have to use single thread model, which

guarantee that no two threads will execute concurrently in the

servlet's service method Allows use of instance variables w/o synchronization This interface is deprecated in the latest servlet specification, since

it doesn’t solve all thread safety issues

public class HelloWorld extends javax.servlet.http.HttpServlet implements javax.servlet.SingleThreadModel{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { // Code here! }}

Environment Access in HTTPServletRequest

getContentLength()getContentType()getProtocol()getServerName()getServerPort()getRemoteAddr()getRemoteHost()getMethod()getServletPath()getPathInfo()getPathTranslated()getQueryString()getRemoteUser()getAuthType()getHeader(“HdrStr”)

Parameter Access in HTTPServletRequest

GetSchemeGetInputStreamGetParameterGetParameterValuesGetParameterNamesGetReaderGetCharacterEncodingGetContentTypeGetCookiesGetRequestURIGetHeaderNames

GetHeadergetIntHeader, getDateHeaderGetSessionGetRequestedSessionIdIsRequestedSessionIdValidisRequestedSessionIDFromCookieIsRequestedSessionIDFromUrlGetHeaderNames

HTTPResponse MethodsGetOutputStreamGetWriterGetCharacterEncodingSetContentLengthSetContentTypeAddCookieContainsHeaderSendErrorSendRedirectSetHeadersetIntHeader, setDateHeaderSetStatusencodeURL, encodeRedirectURL

Session TrackingMany 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 CookieCookie is a small amount of information sent by a servlet to a web browserSaved 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 Servletpublic 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 RewritingURLs can be rewritten or encoded to include session informationURL rewriting usually includes a session IDSession 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 FieldsHidden 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 rememberServlet 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

HttpSessionTo 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 Sessionpublic 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 TimeoutUsed when an end-user can leave the browser without actively closing a sessionSession 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 InvalidationCan 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 MethodsObject getAttribute(String) – Value for the given nameEnumeration getAttributeNames() - All the names of all attributes in the sessionlong getCreationTime() - Time at which this session was createdString getId() - Identifier assigned to this sessionlong getLastAccessedTime() - Last time the client sent a request carrying the identifier assigned to the sessionint getMaxInactiveInterval() - Max time (in seconds) between between requests that the session will be keptServletContext getServletContext() - ServletContext for sessionvoid invalidate() - Invalidates the sessionboolean 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 namevoid removeAttribute(String) - Removes the value for the given namevoid setMaxInactiveInterval(int) - Sets the maximum interval between requests