Object-Oriented Enterprise Application Development Advanced Servlets.

Slides:



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

1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Object-Oriented Enterprise Application Development JavaServer Pages.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
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.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Object-Oriented Enterprise Application Development Introduction to Servlets.
Introduction to Servlet & JSP
Integrating Servlets and JavaServer Pages Vijayan Sugumaran School of Business Administration Oakland University Parts of this presentation provided by.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
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.
Web technologies and programming cse hypermedia and multimedia technology Fanis Tsandilas April 3, 2007.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
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.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 8 Cookies And Security JavaScript, Third Edition.
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.
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
Java Servlets and Java Server Pages Norman White Stern School of Business.
Copyright © 2002 ProsoftTraining. All rights reserved. Java 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.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
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.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
©SoftMooreSlide 1 Session Tracking with Servlets.
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.
Java Servlets and Java Server Pages
Session Tracking Parts of this presentation was provided by SSE.
Introduction To HTML Dr. Magdi AMER. HTML elements.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
1 Servlets – Part 2 Representation and Management of Data on the Web.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Sessions.
Servlet.
Chapter 26 Servlets.
Servlets and Java Server Pages
CS320 Web and Internet Programming Cookies and Session Tracking
Introduction to Servlets
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
CS3220 Web and Internet Programming Cookies and Session Tracking
Web Search Interfaces.
CS3220 Web and Internet Programming Cookies and Session Tracking
Presentation transcript:

Object-Oriented Enterprise Application Development Advanced Servlets

Topics During this class we will examine: Sending data from an HTTP client to a servlet. Responding to an HTTP request. Providing the user with a "shopping cart."

Web Applications

Web Pages (1 of 2) In the modern inter- and intranet worlds, web pages have replaced the old GUI client. Web pages have many advantages over traditional GUI clients: Easier to distribute Easier to maintain Globally available Smaller footprint

Web Pages (2 of 2) For Java servlets to be a true alternative to competing technologies, they must be able to process data from web pages. To manipulate such data, we use the HttpServletRequest object that is passed to the servlet's service() method.

HTTP Requests

Headers The first thing to look at is the content of a browser's request header. The request header provides high-level information about the client that issued the original request. This kind of information is invaluable when writing an application that must be compatible across multiple browsers.

Sample Code – Header (1 of 2) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Header extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter(); 9. out.println(" ");

Sample Code – Header (2 of 2) 10. out.println(" Header "); 11. out.println(" "); 12. Enumeration enum = rqst.getHeaderNames(); 13. while ( enum.hasMoreElements() ) { 14. String name = (String)enum.nextElement(); 15. String value = rqst.getHeader(name); 16. out.println( name + "=" + value ); 17. } 18. out.println(" "); 19. out.close(); 20. } 21.}

Sample Code - Output User-AgentMozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0) Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, application/x-comet, */* Host localhost:8080 Accept-Encoding gzip, deflate Accept-Language en-us Referer Connection Keep-Alive

Name-Value Pairs All data is passed to a servlet as a set of name-value pairs. This approach simplifies the process of passing arguments. This is the same technique used to read initialization parameters from the web.xml file.

Parameters While the request header provides valuable information to the servlet, it doesn't contain the actual data submitted by a web-based form. This data is provided as a set of parameters within the HttpServletRequest. The next code sample illustrates how to access these values.

Sample Code – Parameter (1 of 2) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Parameter extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter();

Sample Code – Parameter (2 of 2) 9. out.println(" "); 10. out.println(" Parms "); 11. out.println(" "); 12. String firstName = rqst.getParameter("firstname"); 13. String lastName = rqst.getParameter("lastname"); 14. out.println( firstName + ", " + lastName ); 15. out.println(" "); 16. out.close(); 17. } 18.}

Passing Parameters Now that we've seen how to access the parameters within our servlet, we need to see how to pass them to the original request. We'll look at two techniques: HTML form tags Direct encoding on the URL

Web Pages The most common way of passing data to a servlet is through a web-based form on an HTML page. This allows us to hide the data from the user. The GET or POST methods change how the data is passed to the servlet.

Sample Code – Parameters Request Parameters Example First Name: Last Name:

Form Tags The FORM tag identifies a set of fields that will be submitted to the servlet as a group. The ACTION identifies the path of the servlet to be executed when the FORM is submitted. The METHOD identifies whether the FORM is submitted using the GET or POST method.

Form Fields (1 of 2) The FORM tag identifies a kind of container to the browser, but it's the individual fields that provide the actual data to the servlet. Each INPUT tag identifies a data source. The NAME of the input is the argument to the getParameter() method. Data is only submitted to the servlet when the form is submitted.

Form Fields (2 of 2) Every form field in a form will be submitted whether or not a value has been provided. If a field has been submitted and it has no value, the getParameter() method will return an empty string. It's the developer's task to perform all necessary typecasts.

GET vs. POST Methods (1 of 3) When the HTML form in the prior example is submitted, you'll see the browser's address bar change to: ?firstname=fred&lastname=flintst one The information appears in the address bar because you used the GET method to submit the form.

GET vs. POST Methods (2 of 3) There are times we don't want this information displayed in the address bar for security or privacy reasons. To avoid displaying the data in the address bar, change the form to submit using the POST method.

Sample Code – Parameters (rev.) Request Parameters Example First Name: Last Name:

GET vs. POST Methods (3 of 3) If you attempt to submit a form using GET or POST (or any other HTTP method) and the corresponding do () isn't defined in the target servlet, you will receive the following message from the web server: HTTP 404 – POST Method Not Supported

Sample Code – Parameter (rev.) (1 of 3) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Parameter extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter();

Sample Code – Parameter (rev.) (2 of 3) 9. out.println(" "); 10. out.println(" Parms "); 11. out.println(" "); 12. String firstName = rqst.getParameter("firstname"); 13. String lastName = rqst.getParameter("lastname"); 14. out.println( firstName + ", " + lastName ); 15. out.println(" "); 16. out.close(); 17. }

Sample Code – Parameter (rev.) (3 of 3) 18. public void doPost(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 19. doGet(rqst, resp); 20. } 21.}

Servlets & State

Stateless Connections Just to keep things lively, most browser's have a stateless relationship to the web server. This means that once a browser closes its connection to the server, the server loses all knowledge of the client. Each request generated by the client results in a new connection to the server.

Maintaining State There are three (3) typical methods for persisting client data across client requests: Cookies Databases Sessions

Cookies (1 of 2) Cookies are small amounts of data that can be written to the client machine. They are actually a name-value pair. When the browser issues a request to a server, all cookies created by that server will be sent along with the request. This technique raises significant issues: Cookies could be disabled within the client.

Cookies (2 of 2) Cookies have specific limitations: There can only be 20 cookies from a given server saved to a user's disk. Each cookie can only be a maximum of 4K for both the name and value combined.

Database We could store all client state data into a database of some sort. This isn't uncommon, but there are still issues: Volume Persistence

Sessions (1 of 2) The servlet specification provides for a class called an HttpSession. It is maintained on the application server and is used to hold whatever data the application chooses to place within it. This allows our application to provide the standard "shopping cart" metaphor.

Sessions (2 of 2) Each session has its own internal identifier called a session id. This value is created by the server and associated with the session when it is created on behalf of a client. Sessions must be created by the application; they are not provided to a client by default.

Sample Code – Session (1 of 4) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class SessionSample extends HttpServlet { 6.public void doGet(HttpServletRequest rqst, HttpServletResponse resp) 7.throws ServletException, IOException { 8. resp.setContentType("text/html"); 9. PrintWriter out = resp.getWriter();

Sample Code – Session (2 of 4) 10. out.println(" "); 11. out.println(" "); 12. out.println(" Session "); 13. out.println(" "); 14. out.println(" "); 15. HttpSession session = rqst.getSession(true); 16. out.println("Session ID: " + session.getId()); 17. out.println(" "); 18. out.println("Created On: " + session.getCreationTime()); 19. out.println(" ");

Sample Code – Session (3 of 4) 20. out.println(" "); 21. out.println("Last Accessed On: " + session.getLastAccessedTime()); 22. out.println(" "); 23. String name = rqst.getParameter("name"); 24. String value = rqst.getParameter("value"); 25. session.setAttribute(name, value); 26. out.println(" "); 27. out.println("Session Data"); 28. out.println(" ");

Sample Code – Session (4 of 4) 29. Enumeration names = session.getAttributeNames(); 30. while (names.hasMoreElements()) { 31. String n = (String)names.nextElement(); 32. Object v = session.getAttribute(name); 33. out.println(n + " = " + v + " "); 34. } 35. out.println(" "); 36. out.println(" "); 37.}

Creating Sessions (1 of 2) To create a session, use the getSession() method on the HttpServletRequest object: public HttpSession getSession() public HttpSession getSession(boolean)

Creating Sessions (2 of 2) We usually want to control when a session is created. It's common practice to include session creation as part of a successful user login. We can check for an existing session when a user attempts to access a page. If the session doesn't exist, we can automatically send the user to a login page.

Storing Values in Session (1 of 2) To store a value into a session object, use the following methods: public void putValue(String name, Object value) public void setAttribute(String name, Object value)

Storing Values in Session (2 of 2) Any data can be stored within the session. The only requirement is that the data be serializable. Serializability is a requirement for most implementations of session distribution.

Recalling Values from Session To recall a value from a session object, use the following methods: public Object getValue(String name) public Object getAttribute(String name)

Other Session Methods There are other useful session methods: public void removeAttribute(String name) public boolean isNew() Public void invalidate()

Session Timeout It is common to specify an application-wide session timeout. As sessions are created an used, they absorb resources such as disk and possible bandwidth. The application has no way of knowing when or even if a user will issue another request that uses the session.

Session Timeout Methods The following methods can be used to manipulate the session timeout value: public void setMaxInactiveInterval(int secs) public int getMaxInactiveInterval()

Session ID (1 of 3) Each session has its own unique identifier. This ID is generated by the application server and cannot be changed using the API. Somehow the server must make the client aware of this ID so that it can be re- submitted on later requests.

Session ID (2 of 3) There are three (3) techniques used to communicate the session ID to the client: Cookies URL Rewriting Hidden Form Fields All of these approaches are transparent to the client and the developer.

Session ID (3 of 3) We typically choose two (2) or more of these techniques when storing a session ID. This allows for variations in browser and client configuration and capabilities.

Retrieving the Session ID Sometimes we might want to access the ID of the session. We may want to store the ID within a database. We can access this ID using the following method on the HttpSession object: public String getId()

Session Distribution To make our application's fault tolerant, many production-grade application servers support session distribution. This means that a user's session is propagated to multiple machines. If the primary machine fails, the user's session is available on the secondary machine.

Namespaces (1 of 2) The names that we give to our session variables are arbitrary. There is a strong possibility that two (2) or more developers on a project will choose identical names for their session values. To avoid this problem, I recommend the use of session "namespaces."

Namespaces (2 of 2) As with namespaces in programming languages, the idea is to ensure that each session variable has a truly unique name. There are several ways of doing this. One approach is to prefix each session variable with the name of the servlet that is responsible for creating it.

Session Wrappers At one client we created a session wrapper class. Its job was to provide a consistent naming scheme for all session names. The name included a "scope" such as global data vs. servlet-specific data. This allowed us to fully qualify any session variable.

Servlet Roles Servlets are typically used as controllers. A request is received from a client, often a web page. The servlet interrogates the request and dispatches to some business entity, often an EJB, to perform some additional processing. At some point a response is sent back to the client, often the result of a JSP.

Separating Business & Presentation Logic To achieve the separation of business logic from presentation, we need the ability to integrate servlets with other J2EE components. This allows us to solve problems that involve a single servlet displaying returning different responses based on the request that was issued.

Request Dispatcher For a servlet to branch, or chain, to another servlet or JSP, it must first get access to a RequestDispatcher object. This object is used to transfer control to the specified URL. This allows us to programmatically choose the next response that will be presented to the client.

Sample Code – Dispatcher (1 of 3) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Dispatcher extends HttpServlet { 6. private void chain(HttpServletRequest rqst, HttpServletResponse resp, String URL) 7. throws ServletException, IOException {

Sample Code – Dispatcher (2 of 3) 8. RequestDispatcher dispatcher = getServletContext(). getRequestDispatcher(URL); 9. dispatcher.forward(rqst, resp); 10. } 11. public void doPost(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException { 12. doGet(rqst, resp); 13. }

Sample Code – Dispatcher (3 of 3) 14. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException { 15. if (rqst.getParameter("uid") == null) 16. chain(rqst, resp, "url1"); 17. else 18. chain(rqst, resp, "url2"); 19. } 20.}

Forward When forward() method of a RequestDispatcher is invoked, the servlet effectively gives up its right to issue any part of the response back to the client. An attempt to use the PrintWriter on the response either before or after a call to forward() will result in an error.

Include If the servlet does need to write data back to the response prior to chaining to another servlet or JSP, then we must use the include() method of the RequestDispatcher class. This method behaves just as the forward() method does save that there are no restrictions on the use of the output stream.

Review During this class we have discussed: Sending data from a web form to a servlet. Processing the parameters of an HTTP request. Providing the user with a "shopping cart." Discussed the HttpSession class. Described techniques useful for dealing with a session object.

Resources Developing Java Servlets James Goodwill, Sam's Publishing, ISBN: Core Servlets and JavaServer Pages Marty Hall, Prentice-Hall, Inc., ISBN: Java 2 Platform, Enterprise Edition B. Shannon, et al., Addison-Wesley, ISBN:

Coming Attractions Next week we'll begin separating the presentation logic from the business logic using JavaServer Pages. Please read Chapters 10 & 11 in your text.