Beyond Java Servlet Programing O'Reilly Conference on Java March, 2000 Copyright 2000, K&A Software.

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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
SIP Servlets. SIP Summit SIP Servlets Problem Statement Want to enable construction of a wide variety of IP telephony.
7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
JSP and Servelets.
JSP and web applications
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Dispatching, monitoring, filtering
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Java Server Pages (JSP)
Apache Struts Technology
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
Web Services Web Services are the basic fundamental building blocks of invoking features that can be accessed by an application program. The accessibility.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Technology Overview JAVA Servlets CS-611 S. Witherspoon.
Object-Oriented Enterprise Application Development Tomcat 3.2 Configuration Last Updated: 03/30/2001.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 Build a Web Application on J2EE. 2 J2EE Scenario Client – Web Server – EIS Resources Client – Web Server – EIS Resources Client – Application Server.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Web Applications Basics. Introduction to Web Web features Clent/Server HTTP HyperText Markup Language URL addresses Web server - a computer program that.
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.
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.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach,
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
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.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
CSC 2720 Building Web Applications
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.
Chapter 5 Being a Web App. Very few servlet or JSP stands alone Many times in our application, different servlets or JSPs need to share information 
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.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
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.
Ch 2 – Application Assembly and Deployment COSC 617 Jeff Schmitt September 14, 2006.
Chapter 6 Server-side Programming: Java Servlets
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
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.
Java Enterprise Edition Programming Page 1 of 9Configuring Servlets Web Application Context Name  In multiple web applications, a “context name” is used.
Servlets.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
1 Web Programming with Servlets & JSP ASSIGNMENT GUIDELINE.
© 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.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
Java Servlets By: Tejashri Udavant..
Pre-assessment Questions
Knowledge Byte In this section, you will learn about:
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Introduction to Java Servlets
Pre-assessment Questions
Presentation transcript:

Beyond Java Servlet Programing O'Reilly Conference on Java March, 2000 Copyright 2000, K&A Software

Introductions Jason Hunter K&A Software Author of "Java Servlet Programming" (O'Reilly)

Overview This talk will:This talk will: –Explain the history of servlets –Describe in detail what's new in API 2.2 –Introduce the exciting new Web Application concept –Show how to use deployment descriptors –Explain the new rules for distributed apps –Describe how to control response buffering –Show the new header manipulation methods –Demonstrate new internationalization support –Explain the new role-based security mechanism –Talk about Project Jakarta If you want an introduction to servlets, THIS IS NOT IT!If you want an introduction to servlets, THIS IS NOT IT!

Servlet Timeline December 1996December 1996 –JavaSoft Servlets first introduced (Java Web Server) June 1997June 1997 –Servlet API 1.0 finalized (JSDK 1.0) December 1997December 1997 –Servlet API 2.0 introduced (JWS 1.1) April 1998April 1998 –Servlet API 2.0 finalized (JSDK 2.0) November 1998November 1998 –Servlet API 2.1 introduced (specification) April 1999April 1999 –Servlet API 2.1 finalized (JSDK 2.1) August 1999August 1999 –Servlet API 2.2 introduced (specification) December 1999December 1999 –Servlet API 2.2 finalized (Jakarta)

Differences From 1.0 to 2.1 Differences between 1.0 and 2.0Differences between 1.0 and 2.0 –Support for internationalization –Support for cookies –Support for built-in session tracking –New SingleThreadModel interface –Support for HTTP/1.1 Differences between 2.0 and 2.1Differences between 2.0 and 2.1 –The API was been "cleaned up" –Support for request dispatching –Support for sharing information via contexts –Support for getting resources in an abstract way –More control over session management –First release of a specification!

Differences From 2.1 to 2.2 Differences between 2.1 and 2.2Differences between 2.1 and 2.2 –Servlets are now part of J2EE –Introduced notion of pluggable Web applications –Clarified rules for back-end server distribution –Added response output buffering –Enhanced control over HTTP headers –Gave new ways to do request dispatching –Provided advanced error handling –Several method signatures have been changed for consistency

Servlets in J2EE The servlet API is now a required API of the Java 2 Platform, Enterprise Edition (J2EE, jatooee)The servlet API is now a required API of the Java 2 Platform, Enterprise Edition (J2EE, jatooee) No real effect to servlet developersNo real effect to servlet developers –Except "servlet engine" has become "servlet container" Enterprise developers are guaranteed support for servlets along with the other enterprise APIsEnterprise developers are guaranteed support for servlets along with the other enterprise APIs –Lucky developers!

Web Applications Web Applications may change the way the Web works.Web Applications may change the way the Web works. –A collection of servlets, JavaServer Pages (JSPs), HTML documents, images, and other Web resources –Portably deployable across any servlet-enabled Web server –Simple install, with full configuration information in the web app –Plug in a search engine, guestbook app, store front, etc Web apps can be deployed using a single archive fileWeb apps can be deployed using a single archive file –Have file extension.war –Stands for "Web application archive" –Created using "jar" tool –Can be digitally signed

This is WAR Inside a war you might find these files:Inside a war you might find these files: On install, a war is mapped to a URI prefix on the serverOn install, a war is mapped to a URI prefix on the server –Assume this war is assigned prefix /demo –/demo/index.html serves index.html –/demo/servlet/CorpServlet serves CorpServlet index.html feedback.jsp images/banner.gif WEB-INF/web.xml WEB-INF/lib/jspbean.jar WEB-INF/classes/CorpServlet.class WEB-INF/classes/com/corp/db/SupportClass.class

Inside WEB-INF WEB-INF contains classes and configuration infoWEB-INF contains classes and configuration info –Modeled after META-INF in JARs –Content is not served directly to the client –WEB-INF/classes contains servlets and supporting class files –WEB-INF/lib contains JAR files, automatically searched –WEB-INF/web.xml is a deployment descriptor The deployment descriptor contains app configuration infoThe deployment descriptor contains app configuration info –It's an XML file with a DTD specified in the Servlet specification

The web.xml File The web.xml deployment descriptor DTD contains over 50 tags to specify:The web.xml deployment descriptor DTD contains over 50 tags to specify: Graphical icon files for the application Graphical icon files for the application –For GUI manipulation A description of the app A description of the app –What the app does, who wrote it, where it can be found A flag indicating whether or not the app can be distributed A flag indicating whether or not the app can be distributed –Distributed apps can be spread across multiple back-end servers, must follow stricter rules than non-distributed apps Parameter information for the app Parameter information for the app –Essentially app-level init parameters

The web.xml File, Cont'd Registered servlet names Registered servlet names –A place to register servlets and give them names Servlet init parameters Servlet init parameters –Alter servlet behavior via params Servlet load order Servlet load order –Which servlets are preloaded, and in what order. URL mapping rules URL mapping rules –Standardized mappings from URLs to servlets –Can be explicit (/foo.html), prefix-based (/lite/*), or extension-based (*.jsp) Session timeout defaults Session timeout defaults –How many minutes of client inactivity before a timeout File extension to MIME type mappings File extension to MIME type mappings –Say.java should be served as text/plain

The web.xml File, Cont'd A welcome file list A welcome file list –An ordered list of files to serve by default ( index.jsp, index.html, index.htm ) Error-handling rules Error-handling rules –Custom handling for error codes or exceptions References to external data sources, such as JNDI References to external data sources, such as JNDI –Add resources into the JNDI lookup table Security constraints Security constraints –Dictate which pages must be protected, and how –Includes built-in form-based authentication For the full DTD seeFor the full DTD see

Web Apps: A Programmer's View To a programmer, a web app corresponds to one ServletContext objectTo a programmer, a web app corresponds to one ServletContext object –All servers have at least a default context –Shared app data can go in the context using setAttribute() and getAttribute() –Each context also has separate HttpSession data Web app parameters are available using context.getInitParameter(String name)Web app parameters are available using context.getInitParameter(String name) The URI prefix can be retrieved with req.getContextPath()The URI prefix can be retrieved with req.getContextPath() –Returns " /demo " or "" for default Make sure not to use the URI prefix with getRequestDispatcher() and getResource()Make sure not to use the URI prefix with getRequestDispatcher() and getResource() –To do so would limit portability

Context Method Example Remember, this code won't compile on most of today's servers.Remember, this code won't compile on most of today's servers. public void doGet(...,...) throws... { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("My context path is: " + req.getContextPath()); out.println("My context parameters are:"); ServletContext context = getServletContext(); Enumeration e = context.getInitParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); Object value = context.getInitParameter(name); out.println(name + ": " + value); } RequestDispatcher dispatcher = context.getRequestDispatcher("/servlet/BuyNow"); dispatcher.include(req, res); }

Lifecycle Clarifications Newly defined: There's exactly one servlet instance per definition (registered name) per context.Newly defined: There's exactly one servlet instance per definition (registered name) per context. –Allows instance variables to hold state information –Servlets did this before, now it's guaranteed to work Also defined: Servlets sharing information via their context must not experience any unexpected ClassCastExceptionAlso defined: Servlets sharing information via their context must not experience any unexpected ClassCastException –Thrown when same class is loaded by different class loaders –So now any servlet reload may cause a full context reload

Distributed Applications Mark an app "distributable" using the deployment descriptorMark an app "distributable" using the deployment descriptor A distributed app must put only Serializable objects in user sessionsA distributed app must put only Serializable objects in user sessions –Supports the server moving data between servers –Server may throw IllegalArgumentException if the stored object is not Serializable –Servers use session affinity for efficiency –(So requests from a particular user are handled by one JVM at a time) A distributed app must use external resources (database, EJB) to share app informationA distributed app must use external resources (database, EJB) to share app information –There's one ServletContext instance per JVM –Information placed into the context is not transferred

Response Buffering In 2.2, servlets can control response bufferingIn 2.2, servlets can control response buffering –Previously servers had control over buffering –Most had buffers around 8K –Now servlets can specify the minimum buffer required This allows flexibility in error handlingThis allows flexibility in error handling –In HTTP the status code (indication of error) must come first –Impossible to set once response has been "committed" with data sent –Larger buffers allow more output to be written before commit

Response Buffering Methods void setBufferSize(int size)void setBufferSize(int size) –Specifies minimum buffer size in bytes –Server may use a larger buffer than requested –Set before writing output! int getBufferSize()int getBufferSize() –Returns actual buffer size boolean isCommitted()boolean isCommitted() –Returns if response is committed void reset()void reset() –Empty buffer and unset headers –Called by sendError() and sendRedirect() void flushBuffer()void flushBuffer() –Sends buffer contents and commits

A Response Buffer Example This servlet demonstrates response buffering in action.This servlet demonstrates response buffering in action. public void doGet(...,...) throws... { res.setBufferSize(16 * 1024); // 16K buffer res.setContentType("text/html"); PrintWriter out = res.getWriter(); // returns or greater int size = res.getBufferSize(); out.println("The client won't see this"); res.reset(); out.println("Nor will the client see this!"); res.reset(); out.println("Nor this if sendError() is called"); if (req.getParameter("important") == null) { res.sendError(400, "important param needed"); }

Support for Double Headers A servlet can now retrieve and set multiple headers of the same name.A servlet can now retrieve and set multiple headers of the same name. Enumeration getHeaders(String name)Enumeration getHeaders(String name) –Returns multiple values for a given header as Enumeration of String objects –Useful for headers like Accept-Language void addHeader(String name, String value)void addHeader(String name, String value) –Adds another value for the given header –Unlike setHeader() which replaces previous values –Also addIntHeader() and addDateHeader() Accept-Language: en Accept-Language: fr Accept-Language: ja

Now This Is Just Temporary Servlets often need to write temporary filesServlets often need to write temporary files –There's now a standard location –Each context has a separate directory –Attribute "javax.servlet.context.tempdir" // The directory is given as a File object File dir = (File) getServletContext().getAttribute( "javax.servlet.context.tempdir"); // Make temp file in temp dir (JDK 1.2) File f = File.createTempFile("xxx", ".tmp", dir); // Prepare to write to the file FileOutputStream fout = new FileOutputStream(f); //...

No More Amnesia Previously servlets had no way to determine their own name!Previously servlets had no way to determine their own name! The name is now available using getServletName()The name is now available using getServletName() –This helps servlets store state information –Using the name as part of the lookup key keeps data unique per instance public void doGet(...,...) throws... { // Inherited from GenericServlet String name = getServletName(); ServletContext context = getServletContext(); Object value = context.getAttribute(name + ".state"); }

So, Where Are You From? More internationalization (i18n) support has been added in 2.2.More internationalization (i18n) support has been added in 2.2. Locale req.getLocale()Locale req.getLocale() –Returns the client's most preferred locale, based primarily on the Accept-Language header Enumeration req.getLocales()Enumeration req.getLocales() –Returns all the client's preferred locales void res.setLocale(Locale loc)void res.setLocale(Locale loc) –Specifies the locale of the response –Automatically sets the Content-Language and Content-Type appropriately –Call this method after calling setContentType(), before getWriter()

Locales in Action This servlet demonstrates the new i18n support:This servlet demonstrates the new i18n support: Note this isn't as powerful as com.oreilly.servlet.LocaleNegotiatorNote this isn't as powerful as com.oreilly.servlet.LocaleNegotiator –See public void doGet(...,...) { res.setContentType("text/html"); Locale loc = req.getLocale(); res.setLocale(loc); PrintWriter out = res.getWriter(); // Write output based on loc.getLanguage() }

Servlet Security A deployment descriptor can set up portable security constraintsA deployment descriptor can set up portable security constraints –Security is role-based –Certain pages can be viewed by users that are part of a given role –For example, only managers can view salary information The deployment descriptor specifies the access granted to each roleThe deployment descriptor specifies the access granted to each role –Role to user or role to group mappings are done during deployment –Server-specific tools facilitate this –Users may come from the server, OS, database, and so on

Servlet Security Methods Two methods were added to support role-based securityTwo methods were added to support role-based security java.security.Principaljava.security.Principal req.getUserPrincipal() req.getUserPrincipal() –Returns a Principal with the name of the client user –Returns null if the user hasn't logged in boolean req.isUserInRole(String role)boolean req.isUserInRole(String role) –Returns true if the current user belongs to the specified role boolean req.isSecure()boolean req.isSecure() –Returns true if the request was made over a secure channel (HTTPS)

Servlet Security Example This example snoops the current security information.This example snoops the current security information. public void doGet(...,...) { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("The current user is: " + req.getUserPrincipal()); out.println("Is the user a Manager? " + req.isUserInRole("Manager")); out.println("Is our connection secure? " + req.isSecure()); }

Better Dispatching API 2.2 has more convenient request dispatching.API 2.2 has more convenient request dispatching. RequestDispatcher context.getNamedDispatcher(String name)RequestDispatcher context.getNamedDispatcher(String name) –Lets a servlet dispatch to a component specified by name instead of URI path Lets components stay "private" Lets components stay "private" RequestDispatcher req.getRequestDispatcher(String path)RequestDispatcher req.getRequestDispatcher(String path) –Lets a user specify a relative URL target –The context.getRequestDispatcher() method must be absolute –No need for that method anymore

Better Redirecting Finally, API 2.2 also makes it more convenient to do simple redirects.Finally, API 2.2 also makes it more convenient to do simple redirects. void res.sendRedirect(String url)void res.sendRedirect(String url) –The redirect URL can now be relative –Clients still demand absolute URLs so the server does translation before sending!

Summary To summarize…To summarize… –Java Servlet API 2.2 makes servlets part of a complete Web application framework –Whole subsections of Web sites can be easily deployed on any Web server that supports API 2.2 –Servlets have solid rules for distribution across multiple back-end servers –Response buffering has been added to make error handling more robust –HTTP header control has been improved –Request dispatching has been made easier with support for relative paths and named dispatchers