90
Lesson 7 Extending Web Server Functionality Servlets and JSP Overview of CORBA

Lesson 7

  • Upload
    wilda

  • View
    32

  • Download
    2

Embed Size (px)

DESCRIPTION

Lesson 7. Extending Web Server Functionality Servlets and JSP Overview of CORBA. Announcements. Homework due a week from Wednesday (May 21). Web Servers. What is a Web Server?. A server program that listens on a standard port and handles http protocol. - PowerPoint PPT Presentation

Citation preview

Page 1: Lesson 7

Lesson 7

Extending Web Server Functionality Servlets and JSPOverview of CORBA

Page 2: Lesson 7

Announcements Homework due a week from Wednesday

(May 21)

Page 3: Lesson 7

Web Servers

Page 4: Lesson 7

What is a Web Server? A server program that listens on a standard port and

handles http protocol. http protocol consists mainly of requests for

documents + upload of file data. Conent type usually html files, text, audio clips,

images, etc. Two most important http protocol elements:

– GET (request document, may upload data)– POST (request document, upload data).

This protocol is typically hidden from you by browser

Page 5: Lesson 7

http protocol Most common elements of http protocol:

– GET, PUT Example

– GET /path/to/file/index.html HTTP/1.0 What does server return?

1. Status line: HTTP/1.0 200 OK 2. Header line: "Header-Name: value“

46 headers defined (host, browser, from, etc.)3. Message body: Content-type/Content-

lengthtext/html, text/gif, etc.

Page 6: Lesson 7

Using telnet to experiment with http Telnet is an application that allows you to

pass arbitrary commands to a specified server.

To connect to a web server:– telnet whatever.whatever.com 80

Once connect try some http commands:– GET /path/to/file.html HTTP1.0

Do some experiments like this to get a feel for the protocol

Page 7: Lesson 7

Role of web browser Web browser hides this protocol underneath

a nice GUI. Web browser also responsible for

displaying content sent back by server – text, html, images, audio.

Broswer must handle server error messages in some elegant way. What errors might be handled by web client itself?

Page 8: Lesson 7

“Stateless” protocol When http server receives connection, it

listens for request, sends response, and then closes connection.

Protocols which allow only a single request per session are called “stateless”.

That is, there is no inherent memory from one connection to the next of the previous action.

Page 9: Lesson 7

Early Web Servers Earliest web sites were static, acted more

like file servers:– Browser requests page– Server hands over page– Browser interprets html and displays to user– Might contain gif or jpeg images or simple

animations

Page 10: Lesson 7

Modern Web Servers Why did this change? E-Commerce became popular: need then arose for

web pages to act more like client-server programs that could interact with user.

On client side, this led to need for higher-end client capabalities:– Java applets– DHTML (css, xml, javascript, etc).– Increased form support in http– multimedia (flash, etc.)

Page 11: Lesson 7

Modern web servers, cont. On server side, this led to:

– dynamic web pages – asp, jsp, servlets, Cold Fusion, PHP, etc.

– improvements in cgi

Page 12: Lesson 7

Modern Web Servers, cont. Problems with client-side processing:

– Slow, must download .class files in case of applet

– Notoriously non-portable– Could not easily access back-end databases.

Bottom line – good for some things but not the final word.

Page 13: Lesson 7

Server-side programming

Page 14: Lesson 7

Server-side programming CGI (Common Gateway Interface) scripts

defined a standard for extending functionality – http GET/POST data could be passed to and

processed in separate function written in any language (C, Perl, Python most typical)

– This often included call to back-end database and response to user via modified html document

Other standards also exist – ISAPI, etc.

Page 15: Lesson 7

Shortcomings of CGI, etc. E-Commerce became more popular and

web sites became more heavily used. This brought to the fore some shortcomings of CGI:– New process spawned for every hit – not

scalable– No concept of sesssion or state at software level– Pretty low level– Security risks (C in particular)

Page 16: Lesson 7

Servlets Java’s form of CGI Relative to CGI, servelets are

– very simple– Relatively high-level

Requirements: a servlet-enabled web server When specified by your web page, web

page passes http requests to java method (assuming everything is setup properly)

Page 17: Lesson 7

Servlets, cont. Servlet method then has access to all of

Java capabilities – jdbc and EJB very important here.

Finally, Servlet writes html back to user. Shift in perspective – up until now, we

wrote the servers (with help sometimes (e.g. CORBA and rmi) ).

Now, we assume server exists and EXTEND its functionality.

Page 18: Lesson 7

Servlets, cont. Important: a web server takes care of all

interactions with the servlet On the client side, servlet pages are

typically requested in one of two ways:– As a regular URL address– As a link in a regular html document

Details are server-dependent

Page 19: Lesson 7

What about the client? Could write our own http-protocol client, but these

also exist already in the form of web browsers Thus, writing client usually boils down to writing

simple html forms Form data automatically passed as String

parameters to servlet Fancier client capabilities require applet – harder

to talk back to server (http tunneling, etc.)

Page 20: Lesson 7

Servlets in J2EE architecture

Page 21: Lesson 7

What is J2EE? In one sense, a model for how to design multi-

tiered (3+) distributed applications One speaks of a J2EE application being made up

of several pieces (we’ll see shortly what these are) Each piece is installed on different machines

depending on its role:– Client-tier components run on the client machine. – Web-tier components run on the J2EE server. – Business-tier components run on the J2EE server. – EIS-tier software runs on the EIS server

Page 22: Lesson 7

Components of J2EE Application

Page 23: Lesson 7

A few things to remember ... J2EE is not a product. J2EE is a specification for a component

architecture and associated software that is needed to support it.

Foremost among such tools is a CTM called the J2EE application server.

Implementors supply the J2EE application server (web container + EJB container) + various others tools for configuring, managing, and deploying J2EE applications.

Page 24: Lesson 7

Pieces that makeup J2EE application

Page 25: Lesson 7

J2EE Components J2EE applications are made up of a number

of different components. A J2EE component is a self-contained

functional software unit that is assembled into a J2EE application with its related classes and files and that communicates with other components

Page 26: Lesson 7

Types of J2EE Components The J2EE specification defines the

following J2EE components: – Application clients and applets are components

that run on the client. – Java Servlet and JavaServer Pages (JSP )

technology components are Web components that run on the server.

– Enterprise JavaBeans (EJB ) components (enterprise beans) are business components that run on the server.

Page 27: Lesson 7

J2EE Clients Web Clients

– “Thin Clients”: no application logic, database queries, etc.

– Web Browser + HTML | XML, etc.– “Recommended” technique– Can include applet if necessary

Application Clients– Typically Swing when richer user interface is needed– Typically access server components directly but can

use http with web server

Page 28: Lesson 7

J2EE Clients

Page 29: Lesson 7

Web Components Either JSP pages or Servlets Regular html pages not strictly considered

Web Components by J2EE standard However, html + support classes typically

bundled with Web Coponents Where do JavaBeans fit in?

Page 30: Lesson 7

Another J2EE View

Page 31: Lesson 7

Mechanics of Writing Servlets

Page 32: Lesson 7

How do I write a Servlet? First, must have some implementation of

the java Servlet API (so that you can import the proper classes).

This does not come with Java 2 SDK, Standard Edition.

It does come with Java 2 SDK, Enterprise Edition (aka J2EE).

Page 33: Lesson 7

Writing Servlets, cont. For servlets (and JSP), Sun’s principle

reference implementation is called Tomcat (www.jakarta.org)

Of course, dozens of vendors supply their own implementation – WebSphere, WebLogic, Jbuilder, etc.

Page 34: Lesson 7

Local Servlet Engine We have installed a Servlet-enabled web server on

polonium.cs.uchicago.edu

It is my _hope_ that we can do all of our work on this and not have to have each person setup their own tomcat locally.

However, there are glitches and we don’t have a professional administrator, so no promises!

Page 35: Lesson 7

Running a servlet Before we see how servlets are

programmed, let’s go through the steps of executing a simple one on polonium.

Steps– Login to polonium.cs.uchicago.edu– cd /usr/share/tomcat4/server/webapps/<username>– Create directory WEB-INF/classes– Place example HelloWorldExample.class servlet file in

this directory

Page 36: Lesson 7

Steps for running servlet, Cont. Steps, cont.

– Go to Tomcat adminstration page. You will need to first create an adminstrator password at https://polonium.cs.uchicago.edu/tomcat/pwd/pwd.cgi

the, to the admin page: https://polonium.cs.uchicago.edu/tomcat/man/manager.cgi– To load a simple unpackaged webapp, go to bottom of page and

add /<username> in “Context Path” box and /usr/share/tomcat4/server/webapps/<username> under “Server Directory Path” box.

– Then click “install” and you should see your application added to the list above. If not, go back and redo, checking everything carefully.

Page 37: Lesson 7

Running servlet, cont. Now you are ready to execute your servlet.

– Go to web browser and enter the following URL

• http://polonium.cs.uchicago.edu:8180/asiegel/servlet/HelloWorldExample

Hopefully, this will display “HelloWorld” in your browser window.

Page 38: Lesson 7

Writing Servlets, cont. All servlets extend the Servlet class. All http servlets (by far most typical) should

extend the HttpServlet class. In extending HttpServlet, you typically

override the following methods:– init, service or doGet/doPost, destroy (very

common)– doPut, doDelete, doOptions, doTrace (rare)

Note: there is NO main() for Servlets!

Page 39: Lesson 7

Main HttpServlet Methods init()

– called once when servlet is loaded by server. Contains any initializations that are common to all requests.

doGet(HttpServletRequest, HttpServletResponse) – Called each time the servlet receives an http GET

request posted by a client. Passes two objects, one representing the information of the request, the other used to configure a response. We’ll study these methods soon.

Page 40: Lesson 7

Main HttpServlet Methods, cont. doPost(HttpServletRequest,

HttpServletResponse)– Same as doGet but for an http POST request.

destroy()– Called before servlet is unloaded from memory.

Performs any final cleanup, freeing memory, closing connections, etc.

Page 41: Lesson 7

Service Method Important: The method

service(HttpServletRequest,HttpServletResponse)

is also called for each servlet invocation. service() in turn calls doGet and doPost, etc.

for an HttpServlet. It is best not to override service even if you

want to handle doGet() and doPost() identically. Simply have one call the other.

Page 42: Lesson 7

HttpServletRequest Object Passed when browser calls doGet and doPost. Most import methods for beginning servlet

programming (in HttpServletRequest class):– String getParameter(String paramName)– String[] getParameterNames()– String[] getParameterValues()

Makes getting data from web pages very simple. Many other methods for images, cookies, etc.

Page 43: Lesson 7

HttpServletResponse Object Passed when browser calls doGet or doPost Most import methods for beginning servlet

programming:– PrintWriter getWriter();

• Get Writer for communicating back to client– setContentType(String);

• Typically use “text/html”, indicating that html will be sent back to the browser

Page 44: Lesson 7

Examples

Page 45: Lesson 7

General Comments Recall that each request for a servlet gets its

own thread but accesses the same methods. Thus, synchronization issues arise.

Writing html to java stream is ugliest thing ever.

Many more servlet classes for having fun. Can’t possibly cover all in one course, but most are very simple.

See http://www.coreservlets.com for more

Page 46: Lesson 7

What is JSP? JSP – Java Server Pages Can be used:

– As alternative to servlets– In combination with servlets

Simplifies ugly aspect of servlet programming (ie writing html to the stream).

Allows you to mix Java code directly with html – output gets sent to stream automatically.

Page 47: Lesson 7

JSP: Making dynamic web content easier

Page 48: Lesson 7

Popular Competing Technologies Microsoft Active Server Pages (ASP)

– Very popular and easy– Locks you into Windows IIS

Perl Hypertext Preprocessor (PHP)– Easy and powerful for certain types of apps– More one-dimensional than java backend world

Cold Fusion– Proprietary

Page 49: Lesson 7

Writing JSP JSP scripting elements inserted directly into

html document Three types of scripting elements

– Expressions: <%= expression %>– Scriptlets: <% code %>– Declarations <%! code %>

Page 50: Lesson 7

JSP Scripting Elements Note: JSP files are translated to servlets

behind the scenes. Knowing this isn’t really necessary but it helps to understand how the JSP scripting elements work:

Expressions are evaluated and automatically placed in the servlet’s output. (ie no need for out.println!).

Page 51: Lesson 7

JSP Scripting Elements, cont. Scriptlets are inserted into the servlet’s

_jspService method (called by service). Declarations are inserted into the body of

the servlet class, outside of any methods.

Any regular html is just “passed through” to the client.

Page 52: Lesson 7

JSP Expressions <= Java Expression %>

– The expression is evaluated when the page is requested, converted to String, and inserted in the web page.

Simple example:– Current time: <%= new java.util.Date() %>

Page 53: Lesson 7

JSP Expressions, cont. To simplify expressions JSP comes with a number

of pre-defined objects. Some important ones are:– Request – Response– Session– Out

Example– Your hostname: <%= request.getRemoteHost() %>

Page 54: Lesson 7

JSP Scriptlets <% Java Code %> If you want to do something more complex

than insert a simple expression. Example:

– <% String queryData = request.getQueryString(); out.println(“Attached GET data: “ +

queryData); %>

Page 55: Lesson 7

Using Scriptlets for conditional output Scriptlets are often used to conditionally

include standard JSP and html constructs. Example

– <% if (Math.random() < 0.5) { %>Have a <B>nice</B> day!<% else { %>Have a <B>lousy<B/> day!<% } %>

Page 56: Lesson 7

Conditional output, cont. This is converted to the following servlet

code:if (Math.random() < 0.5) {

out.prinltn(“Have a <B>nice</B> day!”); } else{ out.println(“Have a <B>lousy</B> day!”); }

Page 57: Lesson 7

JSP Declarations <%! Java Code %> Define methods and fields inserted into main body

of servlet class Declarations do not generate output

– Normally used in conjunction with scriptlets and expressions

Example<%! Private int accessCount = 0; %>

Accesses to page since server reboot:<%= ++accessCount %>

Page 58: Lesson 7

Additional JSP/Servlet features useful for homework Forwarding from a servlet to a jsp page

(common) Forwarding from a jsp page to a servlet (not

so common) or jsp (more common) Session Tracking

Page 59: Lesson 7

Forwarding from Servlet to JSP Very useful when processing result requires

dramatically different presentation to be sent to user

From within servletString url = “/store/login.jsp”;RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(req, res) //pass control to new url dispatcher.include (req, res) //include contents of url

Page 60: Lesson 7

Forwarding from JSP <jsp:forward> page = “Relative URL”/>Example: <% String destination; if (Math.random() > .5){ destination = “/examples/page1.jsp”; } else { destination = “/examples/page2.jsp”;

%><jsp:forward page=“<%= destination %>” />

Page 61: Lesson 7

Session Tracking HTTP is a “stateless” protocol No built-in mechanism to determine whether a

request is associated with a user who has recently issued previous requests.

Typically handled in one of several ways.– Cookies: write info to users disk and retrieve to identify– Hidden Fields, URL-rewriting, etc. (not as good).

Session Tracking API– Layered on top of above mechanisms

Page 62: Lesson 7

Session Tracking mechanics HttpSession s = request.getSession(true)

– Returns session object if request is part of a session, otherwise creates a new session object.

– Use isNew() to determine if sesssion is new.Useful Methods for homeworkpublic Object getValue(String name);public setValue(String name, Object value);public long getLastAccessedTime();

Page 63: Lesson 7

CORBA

Common Object Request Broker Architecture

Page 64: Lesson 7

What is CORBA? Common Object Request Broker Architecture CORBA is a specification for how to design tools

that enable programming with distributed objects. CORBA is a standard, not an implementation. CORBA defines minimum functionality and

interfaces that an implementor must provide to be CORBA-compliant.

Individual vendors sell CORBA implementations. Standard “guarantees” interoperability.

Page 65: Lesson 7

Object Request Broker (ORB) The backbone of CORBA or any D.O. system is

the ORB ORB provides glue code that intercepts local

object calls and marshals/unmarshals for remote machines, other languages, etc.

CORBA specification details how ORB must work: services it provides, interfaces, underlying transport protocol, etc.

CORBA provides other services that are not part of ORB – more on these later.

Page 66: Lesson 7

How CORBA differs from RMI CORBA provides both language and location

transparency. – Very useful even in single address space!

Not governed by a particular vendor Many services on top of simple ORB

– transactions, events, serialization, security, domain-specific stuff, etc.

– Note that many of these already come with Java or its Enterprise extensions.

Typically slower for java to java?

Page 67: Lesson 7

Some Key Concepts/Jargon Distributed Objects

– Typically, objects whose implementations reside on machines other than the client.

OMG – Object Management Group: largest software

consortium in the world Software Specification

– Rules which are used by implementers to create actual software

ORB– Object Request Broker: “middleware” which intercepts

remote object calls and handles marshalling, network communications, inter-language bindings, etc.

Page 68: Lesson 7

CORBA vs. RMI and JNI Typical uses

– Java to java on single machine• Nothing

– Java to java distributed• RMI

– Java to C/C++ single machine• Java native interface (JNI)

– Java to non-C/C++ language single machine• CORBA

– Java to any language distributed• CORBA

Page 69: Lesson 7

Limitations of CORBA

Language-independent means least common denominator approach – missing many features of Java language

Much harder to use complex java objects as arguments/return types.

Inter-orb communication used to be difficult – should be improved now with IIOP

While fairly good at interoperability, portability not a reality.

Must learn IDL, tons of new classes for basic object operations that already exist as part of Java language.

Page 70: Lesson 7

Getting started with CORBA What do you need?

– IDL to whatever language compiler.– Naming registry server– A collection of classes for manipulating CORBA

objects These basic services all come free with JDK1.3. More complete CORBA implementations can be

purchased, e.g. VisiBroker, OrbixWeb, WebSphere, Netscape Communicator (applets)

Page 71: Lesson 7

List of CORBA Services Object life cycle

– Defines how objects are created, removed, moved, and copied

Naming– Defines how CORBA objects can have friendly

symbolic names Events

– Decouples the communication between distributes objects

Page 72: Lesson 7

Services, cont. Relationships

– Provides arbitrary typed n-ary relationships between CORBA objects

Externalization– Like serialization in Java

Transactions– Coordinates atomic access to CORBA objects

Concurrency Control– Like syncrhonized in Java

Page 73: Lesson 7

Services, cont. Property

– Supprots the association of name-value paris with CORBA objects

Trader– Supports the finding of CORBA objects based

on properties describing the service offered by the object

Query– Supports queries on objects

Page 74: Lesson 7

Writing a CORBA application First, you need to get some vendor

implementation of CORBA. There are a huge number covering a large range of complexity, sophistication, additional features, etc.

We have at least 4 vendor CORBA orbs installed on the CS linux cluster.

– ORBit (/opt/ORBit): free, C bindings only– OmniORB (/opt/omniorb): free, C++ bindings only– Visibroker (/opt/vbroker) : fancy, java and C++– jdk (/opt/jdk1.3/jdk) : stripped, java only

Page 75: Lesson 7

Writing a CORBA application Very similar to RMI. Follow these basic steps:1. Write the object interface using CORBA’s IDL

(“interface definition language”). 2. Invoke IDL compiler on target language to

generate needed stub and helper classes (similar to RMI). This can be done for either the server, the client, or both. This generates the interface that the implementation will have to adhere to (think of JNI).

Page 76: Lesson 7

Getting Started, Cont.3. Write the server implementation, using the

target language. Compile the implementation. (You will need to worry about imports and CLASSPATHs here in java, header files in C, etc.)

4. Write the server program that creates and registers the server objects using the Corba naming service (similar to rmiregistry).

Page 77: Lesson 7

Getting Started, Cont.5. Write a client program that looks up the

server objects and invokes services upon them.

6. Start the naming service and server programs, and lastly the client.

Note that you can also bootstrap the registry just as with rmi, so that only a single object needs to be posted and can act as a factory for other objects.

Page 78: Lesson 7

CORBA IDL Best idea is to start with some examples and

hit them with an idl compiler. We’ll do this for idlj, the jdk idl to java compiler.

Pretty fun and simple. Forces you to think about generic objects in language-neutral way.

Maps very naturally into java.

Page 79: Lesson 7

Basic IDL datatypes – Java mappings

IDL Type JAVA Typeboolean booleanchar/wchar charoctet byteshort shortlong intlong long longfloat floatdouble doublestring/wstring string

Page 80: Lesson 7

IDL Language Constructs

IDL Java C++

Module Package Namespace

Interface Interface Abstract class

Operation Method Member function

Attribute Pair of Methods

Pair of functions

Exception Exception exception

Page 81: Lesson 7

Example IDL

Module StoreApp{ interface Store{ string list(); string purchase(in string name, in long quantity); };};

Note that in CORBA parameters are defined as one of theFollowing: - in (will be read only) - out (will be written and need not be initialized) - inout (will be read and written)

Page 82: Lesson 7

CORBA Sample Compile the IDL. On union do:

– /opt/jdk/jdk1.3/bin/idlj –fall store.idl. Idlj is java’s idl-to-java compiler. -Fall says to produce all files, for both client

and server. We’ll separate these later. This will create a bunch of files in a

directory named after your module. You’ll need these when you write your client and server.

Page 83: Lesson 7

CORBA Sample – Writing the Server Writing the server:

– Create a class which extends _<interfaceName>ImplBase.

– For example, for our interface store, we write and implementation which extends.

• _storeImplBase.– Implement all of the methods in the interface,

and add any private instance vars or methods.

Page 84: Lesson 7

Writing the server Implementation

Implementation source code: Store.java

Note that we can use any language for the implementation as long as we have an IDL compiler for that language!

Page 85: Lesson 7

Making the object available Need to write a server program that

carries out the following tasks:

1. Start the ORB2. Create object and register with ORB3. Bind the object to the naming service4. Wait for client invocations

Page 86: Lesson 7

Making the Object Available, Cont. Packages to import for StoreServer.Java

– Org.Omg.CosNaming• NameComponent• NamingContext• NamingContextHelper

– Org.Omg.CosNaming.NamingContextPackage• Provides all exception classes (name not found, etc.)

– Org.Omg.CORBA• ORB

– (Helper classes generated by IDL compiler)

Page 87: Lesson 7

StoreServer.Java, Cont. To start the ORB:

– ORB orb = ORB.Init(args,null); To register an object:

– Store st = new Store();– orb.Connect(st);

To obtain a reference to the naming service– org.omg.CORBA.Object nco =

orb.Resolve_initial_references(“NameService”);

Page 88: Lesson 7

StoreServer.Java, Cont. Use a special CORBA method to cast:

– NamingContext nc = NamingContextHelper.Narrow(nco);

Create a name for the object– NameComponent[] path = {New NameComponent(“store”,”object”)};

Names contain two pieces, ID and KINDNames may also be embedded

Page 89: Lesson 7

SoreServer.java, cont. Bind to the naming service

– nc.rebind(path,st); A trick to wait forever

Object someObject = new Object();synchronized(someObject){ someObject.wait();}

Page 90: Lesson 7

Writing the Client ORB orb = ORB.init(args,null);