J2EE Intro

56
1 J2EE Overview Michael Hogarth, MD Associate Professor, UC Davis School of Medicine Director of Development, CA-EDRS http://www.hogarth.org

Transcript of J2EE Intro

Page 1: J2EE Intro

1

J2EE Overview

Michael Hogarth, MDAssociate Professor, UC Davis School of MedicineDirector of Development, CA-EDRShttp://www.hogarth.org

Page 2: J2EE Intro

Summary

Historical perspectives Common Gateway Interface (CGI) specification Evolution of server-sided processing Server sided Java What is Java? What are Java Servlets? What are Java Server Pages (JSP)? What are Enterprise JavaBeans (EJB)? Anatomy of a J2EE web application Deployment of J2EE applications

Page 3: J2EE Intro

Historical perspectives Useful to understand the current state of web application

frameworks 1989 – HTTP/HTML ‘invented’ by Tim Berners-Lee 1993 – Mosaic Browser developed by Univ of Illinois

National Center for Supercomputing Applications (NCSA) group that included Marc Andreesen Innovations were inline images (<IMG> tag) and launching

external applications by MIME type Made the “Web” graphical and multimedia – the “killer app”

1994 – NCSA introduces CGI specification 1.0 as a method of launching native application on the machine that

ran the web server service (httpd) Converted the Web from ‘static’ content to a multimedia

capable, hypertext ‘window’ into native “legacy” applications October 1994 – Netscape 1.0 release (10 year anniversary next month!)

Page 4: J2EE Intro

CGI Basics

Composed of three parts and one modification Tags to allow capture of information from the user via browser

FORM, checkbox, radio buttons, textbox, textarea, hidden, password

Transfer captured data from Browser to Server Uses the HTTP Header to transfer information upstream to server

Tag that tells the server what process to run and to give it the captured data

ACTION parameter in a FORM tag <FORM ACTION=“/webinquire/profile.jsp”>

Modification = another HTTP command (POST) done because GET, the standard HTTP command to retrieve a web

page was limited to 256 characters in length

Page 5: J2EE Intro

CGI

Server

CGI

HTTPD

Native prog

GET or POST+ data

HTML+variables

Page 6: J2EE Intro

CGI Header Information

Page 7: J2EE Intro
Page 8: J2EE Intro

Early years of CGI Languages

PERL A scripting language designed to streamline UNIX command

(shell) sequences Very popular

UNIX was most prevalent HTTPD platform PERL is interpreted rather than natively compiled (would not crash

computer if coding was bad) Windows PERL port came about for early Windows http servers

(O’Reilly Website 1.0) Introduced the notion of ‘interpreter based’ CGI architecture as

being advantageous Crash safe You could allow multiple users to write their own PERL scripts and

run them without crashing the entire server or conflicting with each other

Page 9: J2EE Intro

Problems with early CGI

Parsing the HTTP header Required that the programmer implement their own

parser – tedious, error-prone A common task

Solution Create program modules that parse the header and

make the data available as language-specific variables

Modules were libraries imported into CGI programs PERL CGI.pm, CGI_C

Page 10: J2EE Intro

Evolution of CGI to languages Clear that interpreted languages were an

advantage – led to “interpreter” engines that had header parsing as a capability (web aware)

iBASIC (1995) Visual Basic interpreter as CGI program Was the basis for Active Server Pages (ASP)

Cold Fusion (1996) Started as a database markup language (DBML)

using ‘tags’ as the command syntax Very easy to use because one did not have to be a

C/C++ programmer to learn tag based syntax Also developed as a interpreter engine as the CGI

module

Page 11: J2EE Intro

Problems with “interpreters” Didn’t scale well

Each invocation of a ‘script’ required loading an entire instance of the interpreter into memory

Would lead to server crashes if too many users They were slow (interpreted) The languages lacked many of the sophisticated

features of standard programming languages No object orientation Syntax lacked good legibility Not many were cross-platform compatible One had to implement one’s own session mechanisms – only

available functionality was ‘cookies’ rather than ‘sessions’ Often programmers developed these poorly leading to security

problems or performance problems

Page 12: J2EE Intro

The birth of server sided Java

Java “Servlets” – Feb 1996Originally released as part of Jeeves, Sun’s

100% Java web server Intended for ‘extending’ the Jeeves server

with java components Servlets are generic HTTP Servlets are subtype of GenericServlet

Jeeves did not support standard CGI Java Servlet mechanism could be used to

accomplish the same objective as CGI

Page 13: J2EE Intro

What are Servlets? “Servlets provide a component-based, platform-

independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. “

Key aspects Refinement of CGI such that the programmer didn’t have to deal

with it any longer Multi-threading of the servlet requests Parsing of the headers (ServletRequest object) Session management - stores session data on the server – key

is stored as a cookie on the client computer

Page 14: J2EE Intro

Servlet vs. CGI

Page 15: J2EE Intro

What is Java? A language (originally called Oak) developed by Bob

Gosling of Sun MicroSytems – development started in 1991

Renamed “Java” by Kim Polese of Sun Goals:

Intended for consumer electronics products in a networked environment

Meant to be an “elegant and clean” language that didn’t invent anything but “had many features cohered immaculately”

Ability to provide seamless operation on multiple platforms Optimize programmer productivity

Minimize ‘bugs’ (pointer problems) Reduce programming overhead required (memory management) Strongly object oriented (multiple inheritance)

Network aware – TCP/IP connection management part of the core language (only language to do that)

Page 16: J2EE Intro

Java history

1995 – Sun’s Java team produced a web browser (Web Runner, later called HotJava Browser)Ran small java programs loaded from a

remote server through the browser (java applets)

Netscape announced it would support java applets in its next release

Page 17: J2EE Intro

Java characteristics

Very strongly object oriented – built to be object oriented from the start (java classes are objects, a program is a collection of classes)

Does not support pointers (source of many difficult-to-trace bugs in C/C++)

Supports Strings as a data type Strongly enforces data types and variable scoping Operator overloading is not supported Objects no longer in use are ‘garbage collected’ by the system

without needing explicit commands in the program (memory management)

Virtual Machine adds portability, security sandboxing, memory management

Page 18: J2EE Intro

Other features of java Javadocs

Standard way of producing documentation for the java classes programming code ‘comments’ placed in certain areas are

parsed by a tool (javadoc) and made into web pages that can be navigated easily

Exception handling Any fatal program crashes/flaws at runtime invoke an

“Exception” that halts the program and reports on the console (or log file) where it halted

In response to these errors, the VM runs the Exception that the class was tied to, the exception is a java program itself that can be made to output an explanation

very useful for debugging or graceful exits Property file loading

Java has a property class in the core API that loads a file and parses name-value pairs into the system for use by the program

JIT – Just In Time compiling Once a java class has been ‘compiled’ by the VM, it is native

code in memory and thus very fast

Page 19: J2EE Intro

How Java changes software development costs Has productivity-enhancing features

Bug reduction: No explicit pointers Referential integrity of objects are checked at compile time Use of true/false reserved words for boolean types (minimize confusion) Type casting is strongly enforced – you can’t cast a String as an Integer

Java source code documentation is automatically rendered as HTML that is easily deployed for others to read

Support inheritance, which allows one to dramatically reduce ‘re-programming’ through re-use

Compiles very quickly (to bytecode) and compiler enforces referential integrity at compile time

Very similar to C/C++ enabling those programmers to transition quickly Unicode character support (strong internationalization support in the

language itself) Arrays are core components of the language (they know their own

size, have array sizing/management functionality) Clean interface mechanisms between java components

Page 20: J2EE Intro

Java lifecycle for all java programs

Java sourcecode

Java “byte”code

Native binaryexecutable

Java “Compiler”javac.exe

Java VirtualMachine (JVM)

happensIn real-time

interpreted

Page 21: J2EE Intro

Java bytecode (intermediate code)

Page 22: J2EE Intro

How did Java come to the Web?

1995 – Netscape supports Sun’s Java AppletsJava programs can be ‘downloaded’ by

accessing a web page and the program is then run on the local machine – Java Applets

Platform neutral, internet-enabled, desktop applications

A direct threat to the Windows desktop dominance

Page 23: J2EE Intro

Back to server sided Java

Applets quickly were shown to be problematic VM incompatibility/versioning issues Slow Security risk GUI was unsophisticated compared to Windows

Java Servlets An advantage over existing server based languages,

particularly for large/complex systems Introduced by O’Reilly in WebSite, the first http server

for Windows (preceeded IIS by 2 years) Slowly took over as the main ‘area’ where Java was

used on the Internet

Page 24: J2EE Intro

What is the Java Servlet API?

Page 25: J2EE Intro

Example Servlet

If request is a GET

Outputting HTML

Page 26: J2EE Intro

How do Servlet engines work?

Server

HTTPD

Servlet RunnerGET or POST

HTML

servlets

HTMLGET/POST

• servlets can be pre-loaded (compiled by the VM into native code and placed into memory) – makes them as fast as native code• servlet invocation creates a new thread not a new instance of the servlet runner

Page 27: J2EE Intro

Problems with Java Servlets Any changes to even a simple output required

recompiling the Servlet, uploading it, and restarting the Servlet engine (disruption in service)

All the View, Data storage/access, and Business logic are together in multiple servlets Difficult to maintain over time

jPortal has >100 servlets and all have database access and output code intertwined!!

Does not align well with object oriented design/UML

Page 28: J2EE Intro

Problem output from Servlets

HTML outputfrom a servlet

Page 29: J2EE Intro

JSP: Dealing with the output HTML output in Servlets had to be ‘printed’ into the

outgoing stream Hard to maintain – any changes to the ‘look&feel’ required

programmers to change source code, recompile, stop the server, upload the new servlet, start the server again

Solution – Java Server Pages Invented by Paul Colton of LiveSoftware, first company to have a

JSP solution for its servlet container JSP are files that have java source code embedded within <%...

%> tags among HTML – they are specialized web pages. The servlet engine simply converts everything outside these tags

into output print statements on the fly Programmers can edit the HTML in JSPs using an HTML editor The JSP/servlet engine will covert the HTML lines into output print

statements and ‘recompile’ into bytecode and reload into memory --- dynamic reloading

Page 30: J2EE Intro

Example JSP page

Java code is embedded within the HTML

Page 31: J2EE Intro

How JSP works

HTTPD

Servlet Runner

servlets

JSP Converter

jsp page (html+java)

Javaservlet

HTML

1. Browser requests JSP page

2. HTTPD recognizes JSP extension means file should be given to JSP/Servlet engine rather than sent back to browser

3. JSP container converts JSP into a java servlet

4. Java servlet is compiled ‘on the fly’ and given to the servlet runner

5. Servlet runner loads servlet and executes it

6. Output from the servlet is given to the HTTPD for return to the browser

Page 32: J2EE Intro

Problems with JSP

Java code in HTML pages – difficult to read the java code and debug

Encourages putting display, data, logic code all together – hard to maintain, not MVC-2

Looping is difficult/error-prone<% Enumeration e = list.elements();

while (e.hasMoreElements()) { out.print("The next name is "); out.println(((ISP)e.nextElement()).getName()); out.print("<br>"); } %>

Page 33: J2EE Intro

Evolution of J2EE Advantages of separating view from business logic and

data storage became apparent (MVC-2 Design Pattern) Enterprise Java Beans (EJB) introduced in 1999 as a

way of isolating server-sided logic into components that were all managed by a container that provided common (and often complicated) runtime management for these components

Sun marketing took Servlets+JSP+EJB+JDBC and packaged them together as a core “enterprise” Java Development Kit called the Java 2 Enterprise Edition, hence the name J2EE

Today also includes Java Messaging (JMS) API, Java Database Connectivity (JDBC), and Remote Method Invocation (RMI)

Page 34: J2EE Intro

Complete J2EE APIs

Page 35: J2EE Intro

Web APIs

Page 36: J2EE Intro

N-tier Web application architecture

Page 37: J2EE Intro

Enterprise JavaBeans (EJB) EJB Container:

“manages security, transactions, and state management, multi-threading, resource pooling, clustering, distributed naming, automatic persistence, remote invocation, transaction boundary management, and distributed transaction management”

Deals with common functionality required in business logic components running on a server

Assumes a generic client-server framework, of which the Web is one of many

Basically, a “java server plug-in architecture” where rather than building/re-building a server connection/security/clustering component, you simply create the functional modules and plug them into such a framework already built (EJB container)

Page 38: J2EE Intro

Writing EJBs An EJB is a java class that implements an interface

and requires certain methods to be correctly implemented

There are two ‘types’ of EJBs: "Entity" bean

Contains persistent data and a specific bean represents a database record containing information.

"Session" bean (service-oriented approach) provides a service, and does not itself represent any persistent

data. a "business logic" bean. any persistent data is in objects passed as a parameter. Any

instance of a session bean can provide the service; they are interchangeable.

The bean is responsible for ensuring appropriate transactional guarantees on its methods.

Page 39: J2EE Intro

EJB CMP

CMP – ‘container managed persistence’EJB 2.0 includes in the specification the

functionality to let the EJB container store the actual data in a relational database

The programmer now only has to deal with objects that they ‘persist’ rather than SQL

Does take a performance hitCan be poorly implemented by the EJB

container maker

Page 40: J2EE Intro

When to use EJB?

EJB’s are not required components of a web application – web apps must be servlets, but can be JSP, and sometimes can invoke EJBs

EJBs are an advantage when: one has business logic that is easily

compartmentalized one needs/wants a high degree of scalability (for

example, distribute processing among multi-machine cluster)

Page 41: J2EE Intro

Further evolution of web application design – enforcing an MVC pattern Jakarta Struts (2001)

Framework that supports and enforces separation between Model and View through a Controller (MVC-2 Design)

Advantages View is not tied to model so view changes can be

done without changing how the model is programmed or designed

Compartmentalizing layers dramatically improves maintainability of the source code (productivity enhancement)

Page 42: J2EE Intro

Early Java Application Design

Java ServletsData

response

request

Problems:• Did not modularize the application and take advantage of object orientation• No shared space for javabeans and other java classes to store/retrieve info

Page 43: J2EE Intro

Model View Controller Design - 1

JSP JavaBeans(object model)

Dataresponse

request

Problems:• Java “glue” and redirection code embedded among HTML – very messy• No shared space for javabeans and other java classes to store/retrieve info

Page 44: J2EE Intro

Model View Controller Design - 2

Servlet(controller)

JSP(view)

redirects

JavaBeans(object model)

Data

response

request

Jakarta Struts:• Provides framework for redirection and shared space for data to be shared among objects• No need to program any servlets, just use one that is supplied (ActionServlet)•Redirection is managed through a configuration file – highly flexible•Errors management functionality – errors messages come from a configuration file and not hard coded•Easy to ‘template’ the view and change that without re-programming

Page 45: J2EE Intro

Next Generation MVC (3?)

Servlet(controller)

JSP(view)

redirects

JavaBeans(object model)

Data

response

request

• Object relational bridge and connection pooling for persisted data• AspectJ – insertion of compiled ‘cross cutting’ functions (common to a group of objects) – for example ‘action logging’, ‘session checking’, etc..

Hibernate

AspectJ

Page 46: J2EE Intro

Java Tag Libraries -- 2002

To decrease the use of embedded java in JSP pages (a maintenance nightmare), java tag libraries have emerged JSP engine invokes specific javabeans or other

processes when it encounters specific tags (<whatever></whatever>)

Original idea – Paul Colton of LiveSoftware -- “java taglets”

Fits well into MVC-2 since javabeans and actions can be represented as “tags” within the HTML and further simplifying the use of java in web application development (HTML authors can put together/modify applications)

Page 47: J2EE Intro

Java tools for web applications today Java Servlets Java Server Pages (JSP) Java Tag Libraries Jakarta Struts JDBC, JMS Enterprise Java Beans (EJB) JavaMail (all e-mail capabilities) JNDI (java naming and directory services) Emerging additional frameworks

Hibernate (object-relational persistence bridge) AspectJ (cross cutting code insertion)

Page 48: J2EE Intro

Anatomy of a J2EE Web Application MVC-2 Designed Apps

typically include: View (JSPs) Controller (one ActionServlet) Model (EJB or javabeans as

needed) Object-relational

bridge/connection pooling (for apps that use databases)

Page 49: J2EE Intro

Deploying J2EE applications Making it simple – web archives and enterprise archives

WAR/EAR - a standardized file packaging for all ‘web applications’ and ‘enterprise applications’

To allow for packaging of an entire application (web pages, jsp, servlets, additional libraries, ejb) in a single file that can be deployed by the server in response to a simple command.

There are over 40 J2EE compliant app servers ranging from very costly to free/open source

Any java ‘web application’, if packaged into a web archive (WAR) according to the specification is deployable on any J2EE app server without modification or re-compiling

“single file” deployment as a .war or .ear file .war and .ear files are packaged using standard zip format and

compression Deployment includes unzipping, loading, and starting that application J2EE servers take care of all this – all one needs to do is to insert

the .war file into the deploy directory and the J2EE server is constantly looking for new ones (auto-deploy feature)

Some servers allow deployment of files by uploading from the desktop, the hitting a deploy button in a web based console…

Page 50: J2EE Intro

J2EE app servers

Sun certifiedJ2EE app servers

Page 51: J2EE Intro

WAR File

Page 52: J2EE Intro

Web.xml file – app config file

Tells the J2EE server:1. how to ‘load’ (load order for servlets)2. which servlets to invoke before the application is made

available to users3. includes authentication functionality4. Mapping (shortname invokes a true java path and class)5. Allows for mapping of a URL pattern or any extension to a

particular servlet (.edrs, for example)6. Also includes some simple authentication functionality

(group, role, authentication)

Page 53: J2EE Intro

Using web.xml for startup params

Page 54: J2EE Intro

J2EE Server Deploys application

WEB-INF is protected fromviewing by the server

Page 55: J2EE Intro

Other relevant tools for Web Application Development jUnit – a unit testing programming API that

facilitates the creation, management, and invocation of unit tests

Cactus – a web-application aware system testing tool (invokes HTTP requests with required parameters and logs the results)

jMeter – a system loading tool to test scalability, bottlenecks, etc..

Java Ant – a java-based and highly configurable MAKE tool (build tool)

Page 56: J2EE Intro

Readings

“Making sense of Java: A guide for managers and the rest of us” (Simpson B.; Manning Publications, 1996)

“Architects of the Web: 1,000 days that built the future of business” (Robert Reid; Wiley and Sons, 1997)

“Designing enterprise applications with the J2EE platform, 2nd ed.” (Iderjeet Singh, Beth Stearns, Mark Johnson; Addison-Wesley, 2002)

“Java 2 platform enterprise edition: Platform and component specifications” (Shannon et al; Addison-Wesley, 2000)

“Programming Jakarta Struts: Building web applications with servlets and JSP”. (Cavaness; O’Reilly Publishing, 2003)