Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Beyond Java Servlet Programing O'Reilly Conference on Java March, 2000 Copyright 2000, K&A Software."— Presentation transcript:

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

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

3 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!

4 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)

5 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!

6 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

7 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!

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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); }

16 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

17 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

18 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

19 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

20 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"); }

21 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

22 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); //...

23 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"); }

24 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()

25 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() }

26 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

27 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)

28 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()); }

29 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

30 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!

31 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


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

Similar presentations


Ads by Google