® IBM Software Group © 2007 IBM Corporation Servlet API (Part II) 4.1.02.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Servlets & JSPs - Sharad Ballepu.
Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Dispatching, monitoring, filtering
Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
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
CS320 Web and Internet Programming Generating HTTP Responses
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.
Servlet details Russell Beale. Servlet lifecycle The servlet container creates only one instance of each servlet Each use request handled with a separate.
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.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach,
Robinson_CIS285Winter2005 Servlets CIS January 2005 Mary Robinson.
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.
Generating the Server Response: HTTP Response Headers.
CSC 2720 Building Web Applications
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
® IBM Software Group © 2007 IBM Corporation J2EE Web Component Introduction
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
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.
Servlets.
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.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
© 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.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Servlets 4 Lec 30 Web Design and Development. Looking Back… Response Redirection  Sending a standard redirect  Sending a redirect to an error page Request.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
Apache Struts Technology A MVC Framework for Java Web Applications.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Speaker Name Speaker Title Speaker Title Oracle Corporation Olivier Le Diouris Principal Product Manager Oracle Corporation Building Servlet and JSP Applications.
Introduction to Servlets
CS320 Web and Internet Programming Generating HTTP Responses
Pre-assessment Questions
Chapter 26 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.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)

2 After completing this unit, you should be able to:  Discuss servlets as controllers (Model-View-Controller architecture)  Look at the processing of request and response headers  Understand how servlets handle redirection  Discuss object sharing  Look at how servlets can forward to or include content from other servlets  Understand the requirements for special characters in HTML documents  Discuss multithreading and thread safety issues  Describe some of the internationalization support for servlets  Understand the use of and need for the servlet context After completing this unit, you should be able to:  Discuss servlets as controllers (Model-View-Controller architecture)  Look at the processing of request and response headers  Understand how servlets handle redirection  Discuss object sharing  Look at how servlets can forward to or include content from other servlets  Understand the requirements for special characters in HTML documents  Discuss multithreading and thread safety issues  Describe some of the internationalization support for servlets  Understand the use of and need for the servlet context Unit objectives

3 Overview of Model-View-Controller (MVC)  Servlet-only applications – servlet acts as model, view, and controller  Poor separation of concerns  Servlet and JavaServer Pages (JSP) applications – the servlet is the controller, the JSP page is responsible for presentation, and other Java classes are the model  Servlets (controller)  JSP page (view)  Business logic (model)  JavaBeans  Enterprise JavaBeans (EJBs)

4 Display Page (JSP) Request Response Forward Interaction Controller (Servlet, JSP) Enterprise Logic and Data Enterprise Servers Third-tier Platforms Application Server Browser Model-View-Controller (MVC)

5 Controller Organization  The Controller establishes the overall control flow in response to a request  At the highest level, the controller must:  Perform precondition checks  Delegate business tasks  Establish state management tasks  The delegate business tasks step typically involves:  Location of appropriate business objects  Delegate computation to business objects  Based on responses, select response agent

6 Processing Request Headers  The request header is built by the Web browser and sent to the Web server  The servlet accesses the request header values from the HttpServletRequest object passed to the doGet or doPost methods  Headers supported differ based on HTTP level  HTTP 1.1 headers are a superset of HTTP 1.0 headers  Query the HTTP level via the HttpServletRequest.getProtocol method  Returns HTTP/1.1 for HTTP 1.1  There are HttpServletRequest methods for standard headers  The getHeaders and getHeaderNames methods return Enumeration objects which provide access to all the header values associated with a particular header name  The getHeader method returns the first (or only) value for the named header

7 Common Headers and HttpServletRequest Methods  Input data type and length  Headers: Content-type and Content-length  Methods: getContentType and getContentLength  Cookies  Header: Cookie  Method: getCookies  Identification for authorization purposes  Header: Authorization  Methods: getAuthType and getRemoteUser  Protocol  Method: getMethod

8 // called by doGet and doPost methods to process request private void processRequest( HttpServletRequest request, HttpServletResponse response) throws... {... // input parameters have been processed String method = request.getMethod(); if (method.equals("GET")) { // special "GET" processing String lang = request.getHeader("Accept-Language"); // lang has the client's language // now set the status and resp. headers // and build the output document } Processing Request Headers (Example)

9 Setting the Response Headers  Can be set via the HttpServletResponse methods setHeader, setDateHeader, and setIntHeader method.  Some headers have their own methods: setContentType, setContentLength, addCookie and sendRedirect  Response headers are required for some status codes:  Document-moved status codes (range 300 to 307) require a Location header  Status code of 401 must have an associated WWW- Authenticate header  Add additional support for your servlet.  Cache-Control (HTTP 1.1) and Pragma (HTTP 1.0) - cache options  Refresh - how soon (in seconds) the browser should ask for an updated page

10 Main type / subtypeDocument type application/pdfAcrobat file (.PDF) application/postscriptPostScript file application/vnd.lotus-notesLotus Notes file application/x-gzipGzip archive application/x-java-archiveJAR file application/zipZip Archive audio/x-wavWindows sound file text/htmlHTML document text/xmlXML document image/gifGIF image Content-Type  The Content-Type header is set via the setContentType method of the HttpServletResponse object  Specifies the Multipurpose Internet Mail Extension (MIME) type of the returned document  Form is main_type/sub_type

11 // process input parms and request headers... // set the return value response.setStatus(HttpServletResponse.SC_OK); // set the document type response.setContentType("text/html"); // turn off caching if (request.getProtocol().equals("HTTP/1.0")) { // HTTP 1.0 response.setHeader("Pragma","no-cache"); } else { // HTTP 1.1 or later response.setHeader("Cache-Control","no-cache"); } response.setDateHeader("Expires", 0); // build the output document... Response Header (Example)

12 Response Redirection and Error Sending  Response Redirect: sendRedirect()  Sends redirection response to client  URL specifies the redirection location  May be absolute or relative  Error Sending: sendError()  Sets a response status code  Server-specific error page describing the error sent as response  Custom pages may be defined for specific codes in Web deployment descriptor

13 private void processRequest( HttpServletRequest request, HttpServletResponse response)... { // process request headers & query data... // redirect to another URL String url = "/YourResults.html"; if (test.equals("Error")) response.sendError(HttpServletResponse.SC_BAD_REQUEST); else response.sendRedirect (response.encodeRedirectURL(url)); return; } Redirection and Send Error (Example)

14 Request Dispatcher  The RequestDispatcher allows you to forward a request to another servlet or to include the output from another servlet  Used to support both forwarding processing to and including response from a variety of local Web resources  For example, JSP pages and HTML files  If a reference to the RequestDispatcher is acquired from the ServletContext  Path information is relative to the ServletContext  If a reference to the RequestDispatcher is acquired from the HttpServletRequest  Path information is relative to the path of the current request

15 Servlet A Servlet B Content returned to Browser forward Content returned to Browser include Request Dispatcher Flow Servlet A Servlet B

16 Sample Use of Request Dispatcher  Forward to a JSP getServletContext(). getRequestDispatcher("/pages/showBalance.jsp"). forward(request, response);  Include static HTML getServletContext(). getRequestDispatcher("/pages/navigation_bar.html").i nclude(request, response);

17 Involving other Resources: Forwarding  To have another resource build the response, use the RequestDispatcher's forward method  getRequestDispatcher(resourceName). forward(request,response)  IllegalStateException is thrown if the source servlet accesses the ServletOutputStream or PrintWriter object Request Dispatcher showBalance.jsp getServletContext().getRequestDispatcher("/pages/showBalance.jsp").forward(request, response);

18 private void processRequest( HttpServletRequest request, HttpServletResponse response)... { // process request headers & query data... // Forward the request if (errorFound) { String res = "/ErrorFound.html"; getServletContext().getRequestDispatcher(res). forward(request, response); return; } Forward Method (Example)

19 Involving other Resources: Including  To have another resource be included in the response, use the RequestDispatcher's include method getRequestDispatcher(resourceName).include(request,response)  The target resource should not set the response headers. If attempted, there is no guarantee that the target values will be used nav_bar.html getServletContext().getRequestDispatcher("/pages/nav_bar.html").include(req, res); Request Dispatcher

20 private void processRequest( HttpServletRequest request, HttpServletResponse response)... { // process request headers & query data... // include the request response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" Start of INCLUDED request"); out.println(" Hi " + request.getParameter("name")); out.flush(); getServletContext().getRequestDispatcher( "/ILSCS01/DispatcherInclude"). include(request, response); out.println(" End of request "); } Include Method (Example)

21 Sharing Objects  There are several ways to share objects between servlets and JSPs:  ServletContext getServletContext().setAttribute("objectName",anObject); getServletContext().getAttribute("objectName");  HttpServletRequest request.setAttribute("objectName",anObject); request.getAttribute("objectName");

22 HttpServletRequest "CUSTOMER" Customer Sharing Objects Example // Servlet "A" public void doGet (HttpServletRequest request, HttpServletResponse resp)... { // process request headers & query data Customer cust;... request.setAttribute("CUSTOMER", cust); String res = "/Internal/ServletB"; getServletContext().getRequestDispatcher(res).forward(request, resp); } // Servlet "B" public void doGet (HttpServletRequest req, HttpServletResponse resp)... { Customer aCust = (Customer) req.getAttribute("CUSTOMER");...} getAttribute() 12 setAttribute()

23 Servlet Context  A Servlet Context defines a group of related servlets  Allows for relative paths  Rooted at a particular point in the URI namespace  Scope for data sharing among servlets  Programmatically accessed via javax.servlet.ServletContext  Servlet Context Attributes  Allows for simple application scoped data sharing between servlets  getAttribute() and setAttribute() methods  ServletContext.getResource  Allows a servlet to load resources specified via a relative path without assuming an absolute directory structure on the server

24 /Rooms /HRApps/Personnel /Hire /DisplayRooms /Login /Retire Servlet Context /HRApps/Personnel Servlet Context /Rooms Web container servlet Web Containers and Servlet Context

25 Client Sue Client Bob ServletRequest ServletResponse ServletConfig ServletContext ServletResponse ServletRequest Thread 1 Thread 2 Servlet A Servlet Objects (1 of 2)

26 Client Sue Client Bob ServletRequest ServletResponse ServletConfig ServletContext ServletResponse ServletRequest Servlet A Thread 1 Servlet B Thread 2 ServletConfig Servlet Objects (2 of 2)

27 Internationalization  Accepting Locale  Communicated from the client using the Accept-Language header  Use getLocale() and getLocales() methods of the ServletRequest interface to get the locales client will accept content in  Setting Locale  Use setLocale() method of the ServletResponse interface to set the language attributes of a response  setLocale() method should be called before the getWriter() method of the ServletResponse interface is called  Default encoding of a response is ISO if none has been specified

28 Checkpoint 1.How do you forward a request to another servlet? 2.How can you pass an object to a servlet you are forwarding to? 3.How can you include dynamic content generated by another servlet? 4.What is the servlet context? 5.What servlets share a servlet context?

29 Checkpoint solutions 1.Use the request dispatcher to invoke the target servlet: getServletContext().getRequestDispatcher (“/servlet/MyServlet”).forward(req, res); 2.Set the object as an attribute to the HttpServletRequest. The target servlet can then getAttribute() and cast it to the proper type. You call also use the session or the servlet context. 3.Use an include() to temporarily give control to another servlet. 4.The servlet context is an execution context of a group of related servlets. It allows for the servlets to use relative paths to refer to each other, and provides another way to share objects between servlets. Servlets within the same servlet context are defined in the same Web application. 5.Servlets defined within the same Web application share a servlet context.

30 Having completed this unit, you should be able to:  Discuss servlets as controllers (Model-View-Controller architecture)  Look at the processing of request and response headers  Understand how servlets handle redirection  Discuss object sharing  Look at how servlets can forward to or include content from other servlets  Understand the requirements for special characters in HTML documents  Discuss multithreading and thread safety issues  Describe some of the internationalization support for servlets  Understand the use of and need for the servlet context Having completed this unit, you should be able to:  Discuss servlets as controllers (Model-View-Controller architecture)  Look at the processing of request and response headers  Understand how servlets handle redirection  Discuss object sharing  Look at how servlets can forward to or include content from other servlets  Understand the requirements for special characters in HTML documents  Discuss multithreading and thread safety issues  Describe some of the internationalization support for servlets  Understand the use of and need for the servlet context Unit summary