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

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Servlets and a little bit of Web Services Russell Beale.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Servlets CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Lecture 10 Server-side Programming: Java Servlets.
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
CSC 2720 Building Web Applications
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class.
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
©SoftMooreSlide 1 Session Tracking with Servlets.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Session Tracking Parts of this presentation was provided by SSE.
SERVLET THETOPPERSWAY.COM
How CGI and Java Servlets are Run By David Stein 14 November 2006.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Web Computing: Servlet CS587x Lecture 10 Department of Computer Science Iowa State University.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Java Servlets References: Karen Anewalt, Mary Washington College.
CS122B: Projects in Databases and Web Applications Spring 2017
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Sessions.
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
All You Ever Wanted To Know About Servlets
CS122B: Projects in Databases and Web Applications Spring 2018
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
CS122B: Projects in Databases and Web Applications Winter 2019
Servlet Session Tracking: Session API
Presentation transcript:

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

Web Computing: Servlets CS587x Lecture Department of Computer Science Iowa State University

What to cover Introduction on servlet Servlet architecture Servlet programming and example Session management Cookie URL rewriting Hidden form field HttpSession

What is a Servlet A 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 HTTP The 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 process The servlet returns a response to the web server The web server forwards the response to the client Client (web browser) Web Server HTTP request HTTP response Servlet Container 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 engines E-commerce applications Shopping carts Product catalogs Personalization systems Intranet application Groupware applications: bulletin boards, file sharing, etc.

Steps of Servlet Processing 1. 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 servlets Servlets 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 Similarities GET and POST methods look the same to servlets Can 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 Servlet import 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 (" Hello World "); pw.flush(); pw.close(); }

Running Servlets Jakarta/Apache Tomcat Supercedes Java Apache and JServ Macromedia JRun ServletExec Weblogic Borland Enterprise Application Server/JBuilder Java Servlet Development Kit (JSDK)

Single Threaded Example By 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- safe In 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 GetScheme GetInputStream GetParameter GetParameterValues GetParameterNames GetReader GetCharacterEncoding GetContentType GetCookies GetRequestURI GetHeaderNames GetHeader getIntHeader, getDateHeader GetSession GetRequestedSessionId IsRequestedSessionIdValid isRequestedSessionIDFromCookie IsRequestedSessionIDFromUrl GetHeaderNames

HTTPResponse Methods GetOutputStream GetWriter GetCharacterEncoding SetContentLength SetContentType AddCookie ContainsHeader SendError SendRedirect SetHeader setIntHeader, setDateHeader SetStatus encodeURL, encodeRedirectURL

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: /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 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, ed 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(" "); 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 (" "); 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 usrs during a period of 30 minutes 4K bytes of data per session 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