Web Applications. For live Java training, please see training courses at



Similar documents
Web Applications. Originals of Slides and Source Code for Examples:

& JSP Technology Originals of Slides and Source Code for Examples:

Debugging Ajax Pages: Firebug

Building Web Services with Apache Axis2

Controlling Web Application Behavior

Server Setup and Configuration

An Overview of Servlet & JSP Technology

JHU/EP Server Originals of Slides and Source Code for Examples:

2011 Marty Hall An Overview of Servlet & JSP Technology Customized Java EE Training:

Application Security

Java with Eclipse: Setup & Getting Started

Creating Java EE Applications and Servlets with IntelliJ IDEA

Volume 1: Core Technologies Marty Hall Larry Brown. An Overview of Servlet & JSP Technology

Android Programming: Installation, Setup, and Getting Started

Web Container Components Servlet JSP Tag Libraries

What servlets and JSP are all about

Servlet and JSP Filters

In this chapter, we lay the foundation for all our further discussions. We start

Java Servlet 3.0. Rajiv Mordani Spec Lead

Session Tracking Customized Java EE Training:

Web Application Programmer's Guide

Web Application Architecture (based J2EE 1.4 Tutorial)

Handling the Client Request: Form Data

Struts 2 - Practical examples

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

The Google Web Toolkit (GWT): Overview & Getting Started

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Workshop for WebLogic introduces new tools in support of Java EE 5.0 standards. The support for Java EE5 includes the following technologies:

Virtual Machine (VM) For Hadoop Training

Web Applications and Struts 2

SSC - Web applications and development Introduction and Java Servlet (II)

Building and Using Web Services With JDeveloper 11g

PowerTier Web Development Tools 4

Getting Started with Web Applications

Java Web Programming. Student Workbook

CS Developing Web Applications with Java Technologies

Model-View-Controller. and. Struts 2

Understanding class paths in Java EE projects with Rational Application Developer Version 8.0

Programming on the Web(CSC309F) Tutorial: Servlets && Tomcat TA:Wael Aboelsaadat

Hello World Portlet Rendered with JSP for WebSphere Portal Version 4.1

Apache Pig Joining Data-Sets

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

WebSphere v5 Administration, Network Deployment Edition

Web Frameworks and WebWork

Course Name: Course in JSP Course Code: P5

Crystal Reports for Eclipse

INTRODUCTION TO WEB TECHNOLOGY

Struts Tools Tutorial. Version: M5

Piotr Nowicki's Homepage. Java EE 6 SCWCD Mock Exam. "Simplicity is the ultimate sophistication." Important!

Oracle Hyperion Financial Management Custom Pages Development Guide

Java and Web. WebWork

Installing and Running Tomcat 5.5

Developing Web Applications using JavaServer Pages and Servlets

Glassfish, JAVA EE, Servlets, JSP, EJB

Virtual Open-Source Labs for Web Security Education

Hadoop Streaming coreservlets.com and Dima May coreservlets.com and Dima May

2. Follow the installation directions and install the server on ccc

Deploying a Logi Info Application on WAS

Configure a SOAScheduler for a composite in SOA Suite 11g. By Robert Baumgartner, Senior Solution Architect ORACLE

Design Approaches of Web Application with Efficient Performance in JAVA

Java Server Pages combined with servlets in action. Generals. Java Servlets

CREATE A CUSTOM THEME WEBSPHERE PORTAL

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

JBoss SOAP Web Services User Guide. Version: M5

Official Android Coding Style Conventions

PA165 - Lab session - Web Presentation Layer

ServletExec TM 6.0 User Guide. for Microsoft Internet Information Server Sun ONE Web Server Sun Java System Web Server and Apache HTTP Server

Tutorial: setting up a web application

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Advanced Java Client API

WIRIS quizzes web services Getting started with PHP and Java

ServletExec TM 5.0 User Guide

The Google Web Toolkit (GWT): The Model-View-Presenter (MVP) Architecture Official MVP Framework

A Guide to Understanding Web Application Development Corey Benson, SAS Institute, Inc., Cary, NC Robert Girardin, SAS Institute, Inc.

Application Notes for Packaging and Deploying Avaya Communications Process Manager Sample SDK Web Application on a JBoss Application Server Issue 1.

Rapid Application Development. and Application Generation Tools. Walter Knesel

TIBCO ActiveMatrix BPM Web Application Component Development. Software Release 2.0 November 2012

Course Number: IAC-SOFT-WDAD Web Design and Application Development

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

CONTROLLING WEB APPLICATION BEHAVIOR WITH

Java Servlet Tutorial. Java Servlet Tutorial

Web Development on the SOEN 6011 Server

Java Web Programming with Eclipse

The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics

L01: Using the WebSphere Application Server Liberty Profile for lightweight, rapid development. Lab Exercise

JBoss Portlet Container. User Guide. Release 2.0

Oracle Hyperion Financial Management Developer and Customization Guide

FireBLAST Marketing Solution v2

Map Reduce Workflows

Ch-03 Web Applications

Managed Beans II Advanced Features

1 How to install CQ5 with an Application Server

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

Mastering Tomcat Development

Consuming, Providing & Publishing WS

Transcription:

2009 Marty Hall Using and Deploying Web Applications Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/msajsp.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2009 Marty Hall For live Java training, please see training courses at http://courses.coreservlets.com/. coreser com/ Servlets, JSP, Struts, ts JSF, Ajax, GWT, Java 5, Java 6, Spring, Hibernate, JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, Customized or customized Java EE Training: versions http://courses.coreservlets.com/ can be held on-site at your Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. organization. Contact hall@coreservlets.com for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Agenda Purpose of Web applications Structure of Web applications Setting up Web applications with Tomcat Sharing data among Web applications 4 Idea of Web Applications 5 Single directory or file Servlets, JSP pages, HTML files, utility classes, beans, tag libraries, etc. are bundled together in a single directory hierarchy or file Common URL prefix Access to content in the Web app is always through a URL that has a common prefix http://host/webappprefix/blah/blah web.xml controls many things Many aspects of Web application behavior controlled through deployment descriptor (web.xml) The deployment descriptor is covered in detail in the next section.

Purposes of Web Applications 6 Organization Related files grouped together in a single file or directory hierarchy. HTML files, JSP pages, servlets, beans, images, etc. Portability All compliant servers support Web apps. Can redeploy on new server by moving a single file. Separation Each Web app has its own: ServletContext Class loader Sessions URL prefix Directory structure Structure of a Web Application 7 JSP and regular Web content (HTML, style sheets, images, etc.): Main directory or a subdirectory thereof. Servlets: WEB-INF/classes (if servlet is unpackaged i.e. in default package) A subdirectory thereof that matches the package name. Unjarred beans and utility classes: Same place as servlets (but always use packages!) JAR files: WEB-INF/lib. web.xml: WEB-INF Tag Library Descriptor files: WEB-INF or subdirectory thereof Files in WEB-INF not directly accessible to clients Server can use RequestDispatcher to forward to pages in WEB-INF

Example Deployment Structure 8 Installing Eclipse Overview Eli Eclipse is a free open-source development environment with support for Java and many other languages Downloading http://www.eclipse.org/downloads/ Choose "Eclipse IDE for Java EE Developers" As of 8/2008, version 3.4, called Eclipse Ganymede Installing Unzip into directory of your choice Put shortcut to eclipse.exe on your desktop Integrating Tomcat in Eclipse http://www.coreservlets.com/ com/ Apache-Tomcat-Tutorial/eclipse.html 9

Configuring Eclipse Make sure Eclipse knows about Tomcat Click on Servers tab at bottom. R-click in window. New, Server, Apache, Tomcat v6.0, Next, navigate to folder, Finish. Suppress unnecessary compiler warnings Window Preferences Java Compiler Errors/Warnings Change "Serializable class without..." to "Ignore" 10 Making Web Apps in Eclipse Make empty project File New Project Web Dynamic Web Project Giveitaname(eg it (e.g., "test") Accept all other defaults Shortcut If you have made Dynamic Web Project recently in workspace, you can just do File New Dynamic Web Project 11

Adding Code to Eclipse Projects 12 Locations src Unpackaged Java code Packages strongly recommended src/somepackage Java code in somepackage package WebContent Web files (HTML, JavaScript, CSS, JSP, images, etc.) WebContent/some-subdirectory Web content in subdirectory WebContent/WEB-INF t/web web.xml (will be discussed later) Can also click on "Deployment Descriptor" Note Can cut/paste or drag/drop files into appropriate locations Starting Server in Eclipse 13 Start Tomcat Select "Servers" tab at bottom R-click on Tomcat Choose "Start" Verify server startup Open browser Enter http://localhost/ You should see blank directory listing If you want pretty Tomcat welcome page, search for a folder called ROOT in your Eclipse workspace. Copy files from C:\tomcat-dir\webapps\ROOT to that folder

Deploying App in Eclipse Deploy project Select "Servers" tab at bottom R-click on Tomcat Choose "Add and Remove Projects" Choose project Press Add Click "Finish" Restart Server R-click Tomcat at bottom Restart 14 Testing Deployed Apps in Eclipse 15 Start a browser Eclipse also has builtin browser, but I prefer to use Firefox or Internet Explorer Test base URL http://localhost/test/ Test Web content http://localhost/test/hello.html html (case sensitive!) http://localhost/test/hello.jsp If you used subdirectories es http://localhost/test/ some-subdirectory/blah.html Test servlets http://localhost/test/servlet/helloservlet http://localhost/test/servlet/coreservlets.helloservlet2 Note: custom URLs discussed in next section

Eclipse Structure (IDE-specific) vs. Deployment Structure (Standard) 16 Java code Eclipse src/subdirmatchingpackage HTML, JSP, Images WebContent WbC WebContent/randomDir web.xml WebContent/WEB-INF Deployed Java code deploydir/webappname/ WEB-INF/classes/ subdirmatchingpackage HTML, JSP, Images deploydir/webappname deploydir/webappname/ randomdir web.xml deploydir/webappname/ WEB-INF Note On Tomcat, deploydir is tomcat_installdir/webapps Making Custom Web Apps Manually 17 1. Make a directory called app-blank app-blank/web-inf/web.xml (copy from mine) app-blank/web-inf/classes (empty) 2. Copy/rename E.g., copy app-blank and call it myapp 3. Put code in proper place in myapp Web content (HTML, JSP, images, etc.) goes in the top-level directory (myapp) or any subdirectory other than WEB-INF (e.g., myapp/somedir) Servlets and other classes go in a subdirectory of WEB- INF/classes that matches the package age name. 4. Copy app to deployment directory On Tomcat, entire directory goes in install_dir/webapps 5. Update your CLASSPATH. Add webappdir/web-inf/classes to it. Not usually needed if you have ".." in the CLASSPATH

Manual Web App Development Strategy with Tomcat 18 Development Keep the original of your Web app directory in your development directory. Have all the files in the proper location within that Web app directory. Deployment Copy the entire Web app directory to the server's deployment location (e.g., to install_dir/webapps). I keep a shortcut to webapps and drag the Web app dir onto the shortcut with the R mouse and then say "Copy". CLASSPATH Must include the top-level development directory That now means WEB-INF/classes dir of your Web app If your CLASSPATH has "..", you can leave CLASSPATH unchanged as long as you avoid nested packages Changing the Web App Prefix Eclipse default: project name is Web App prefix So, if project is named foo, when you deploy locally the URL is http://localhost/foo/whatever Tomcat default: folder name is Web App prefix So, if you deploy the folder bar to tomcat_dir/webapps, the URL is http://localhost/bar/whatever. Custom prefix in Eclipse R-click on project, then Properties Web Project Settings Context Root Custom prefix in Tomcat Edit tomcat_dir/conf/server.xml 19

Defining Custom URLs 20 Java code package mypackage;... public class MyServlet extends HttpServlet {... } web.xml entry (in <web-app...>...</web-app>) Give name to servlet <servlet> <servlet-name>myname</servlet-name> <servlet-class>mypackage.myservlet</servlet-class> </servlet> Give address (URL mapping) to servlet <servlet-mapping> <servlet-name>myname</servlet-name> <url-pattern>/myaddress</url-pattern> </servlet-mapping> Resultant URL http://hostname/webappprefix/myaddress Defining Custom URLs: Example (Assume Eclipse Project is "test") <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee"... version="2.5"> Don't edit this manually. Should refer to version 2.4 or 2.5 (Tomcat 6 only). 21 <!-- Use the URL http://hostname/intro/hi instead of http://hostname/intro/servlet/helloservlet --> <servlet> <servlet-name>second Hello Servlet</servlet-name> <servlet-class>coreservlets.helloservlet2</servlet-class> </servlet> Fully qualified classname. Any arbitrary name. <servlet-mapping> But must be the same both times. <servlet-name>second Hello Servlet</servlet-name> <url-pattern>/hi2</url-pattern> / l </servlet-mapping> </web-app> The part of the URL that comes after the app (project) name. Should start with a slash.

Defining Custom URLs: Result 22 Eclipse details Name of Eclipse project is "test" Servlet is in src/coreservlets/helloservlet2.java Deployed by right-clicking on Tomcat, Add and Remove Projects, Add, choosing test project, Finish, right-clicking again, Start Failing to Define Custom URLs You should always use custom URLs on deployed d projects URLs look cleaner and simpler and shorter URLs have more meaningful names You don't expose possibly proprietary class file names You can use web.xml to assign init params later Does not work with /servlet/mypackage.myservlet You can apply filters and security settings later (via web.xml) in a more predictable and controllable manner Most importantly of all, you can avoid being added to Marty s Hall of Shame The kiss of death for any self-respecting Java EE developer 23

The Hall of Shame (Deployed Sites with Ugly /servlet/ URLs) 24 The Art of WAR (Files) 25 WAR files are simply JAR files with a different file extension And JAR files are simply ZIP files All servers are required to support Web apps that are in WAR files Technically, they are not absolutely required to support unbundled Web apps. To create a WAR file, change directory to top-level Web app directory and do: jar cvf webappname.war * Or use WinZip (or "Create Compressed dfolder" on XP) Eclipse can build WAR files automatically R-click project, Export WAR file Registering is still server-specific specific Tomcat: just drop WAR file in install_dir/webapps webappname becomes Web application URL prefix

26 Handling Relative URLs: Problem Individual JSP or HTML page: easy to load image from relative location <IMG SRC="EvilEmpire.gif" > <IMG SRC="redmond/EvilEmpire.jpg jpg" > What about servlets? Same strategy doesn't work Default servlet URL: http://host/prefix/servlet/name Browser, not server, resolves relative URL What if same image is used by JSP or HTML pages scattered throughout app? Same problem Also same problem: Style sheets, applets, even regular hypertext links Handling Relative URLs: Solutions Use the Web application name in the URL. <IMG SRC="/webAppPrefix/redmond/Borg.gif"...> Use web.xml to assign URLs that are at the top level of the Web application Change http://host/webappprefix/servlet/somename to just http://host/webappprefix/somename pp More useful for servlets than for JSP Use getcontextpath Call request.getcontextpath() and add result to URLs by hand 27

Velocity, WebMacro, and Other Alternatives to JSP Technology Issues Standardization Portability Integration Industry support Technical features Arguments for alternatives focus almost exclusively on last issue Even if proponents were right about all their technical arguments, would that matter? 28 29 Alternatives to JSP Technology: Integration Issues Web apps give standard location for: Servlets, JSP pages, and regular Web content t Not for Velocity or WebMacro pages Security settings apply to Servlets, JSP pages, and regular Web content Not Velocity or WebMacro pages Initialization parameters defined for Servlets and JSP pages Not Velocity or WebMacro pages Filters apply to Servlets, JSP pages, and regular Web content Not Velocity or WebMacro pages Listeners apply to Servlets, JSP pages, and regular Web content Not Velocity or WebMacro pages

30 Sharing Data Among Web Applications Failure: Sessions. Each Web app has its own set of sessions. Standard ServletContext. Each Web app has a separate one. Static methods or fields. Each Web app uses a different ClassLoader. Success: Explicit cookies. Cookies are shared by the whole site (even the whole top-level domain if set appropriately). p Be sure to do cookie.setpath("/"), however. ServletContext associated with a specific URL. ServletContext mycontext = getservletcontext(); String url = "/somewebappprefix"; ServletContext othercontext = mycontext.getcontext(url); Object somedata = othercontext.getattribute("somekey"); Setting Shared Data: Example 31 public class SetSharedInfo extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getsession(true); session.setattribute("sessiontest","session Entry One"); ServletContext context = getservletcontext(); context.setattribute("servletcontexttest", "Servlet Context Entry One"); Cookie c1 = new Cookie("cookieTest1", "Cookie One"); c1.setmaxage(3600); // One hour response.addcookie(c1); // Default path Cookie c2 = new Cookie("cookieTest2", "Cookie Two"); c2.setmaxage(3600); // One hour c2.setpath("/"); // Explicit path: all URLs response.addcookie(c2); String url = request.getcontextpath() + "/servlet/moreservlets.showsharedinfo"; // In case session tracking is based on URL rewriting. url = response.encoderedirecturl(url); response.sendredirect(url); }}

Displaying Shared Data: Example 32 public class ShowSharedInfo extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); String title = "Shared Info"; out.println(servletutilities.headwithtitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n"+ " "); HttpSession session = request.getsession(true); ServletContext application = getservletcontext(); application = application.getcontext("/sharetest1"); tc t t("/ t1") Cookie[] cookies = request.getcookies(); 33 Accessing Web App Data: Case 1 SetSharedInfo run from sharetest1 ShowSharedInfo also run from sharetest1 Results Found: session data Found: servlet context data from normal servlet context Found: servlet context data when explicitly requesting servlet context from sharetest1 Found: all cookies

34 Accessing Web App Data: Case 2 SetSharedInfo run from sharetest1 ShowSharedInfo run from sharetest2 Results Not found: session data Not found: servlet context data from normal servlet context Found: servlet context data when explicitly requesting servlet context from sharetest1 Not found: cookies that had default path Found: cookies with / as path Summary 35 Web application benefits Easy organization and deployment Isolation from other applications Structure Top-level directory or subdirectory other than WEB-INF: JSP, HTML, other Web content WEB-INF web.xml WEB-INF/classes/directoryMatchingPackage Servlets, beans, utilities Creating a Web app in Eclipse Mk Make a new Dynamic Wb Web project. Eclipse will create deployment structure automatically. Creating a Web app in Tomcat Make a directory with proper structure t (e.g. WEB-INF and WEB-INF/classes subdirectories) Copy to tomcat_dir/webapps.

2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.