Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
1.264 Lecture 15
Web development environments:JavaScript
Java applets, servletsJava (J2EE)
Active Server Pages
Development environments
• XML, WSDL are documents• SOAP is HTTP extension• UDDI is a directory/registry of services, sites
– Allow servers, services to be found• Browsers and client apps can handle these new protocols
– Less need for dynamic content to be downloaded• Servers must generate and receive XML, SOAP,…
– Straightforward extensions to HTTP, MIME types• Java (J2EE) and Active Server Pages (ASP.NET) are the
server environments that manage this– Java (J2EE) and C#, C++ and Visual Basic (ASP) are
programming languages used on servers• Scripts and applets are used on the client side, but are
relatively less important– JavaScript, VBScript, Java applets are used on clients
Java, JavaScript, Java Beans…• Developed independently by Sun (Java, Java Beans) and
Netscape (JavaScript)– Java and JavaScript, by chance, released in Netscape Navigator
2.0• JavaScript, JavaScriptBeans (JS components):
– Scripting language for HTML pages, using several new tags– Can run on either browser (client) or Web server
• Java:– Full programming language: Web and general programming– Java applets: Limited Java programs running on browser
(client)– Java servlets: Full featured Java programs running on Web
server• Java Beans: Java programming language components
– Component model with standard interfaces (on server)– PME (properties, methods, events) paradigm
• Enterprise Java Beans: database-oriented Java component– Database transaction components: load balancing, rollbacks,– Session components: maintaining state
• Java Server Pages:– Simpler way of writing Java servlets on the Web server<-
------
- ---R
un o
n se
rver
- --- - -
- - -- - -
- - -- - -
-- --- >
- --- -R
un o
n cl
ien t
- --- - >
Script basics (Java Script, VB Script)• Script is program run on client or server in response to browser
request– Early scripts (Common Gateway Interface, or CGI) run on server only– Modern script languages (VBScript, JavaScript) run on client or
server• JavaScript, VBScript are at least three times faster than CGI on server
– Active Server Pages specifies scripts to run on client and/or server• Web scripts can be written in many languages
– Perl, C are typical choices in the past (and present) for server only– VBScript and JavaScript are major options now for client– “Server side includes” are a very simple script capability
• Include server variables, files, command outputs in html page sent to browser. SSI runs on server only.
• First part of this lecture focuses on scripts, primarily running on the browser– These client scripts are loosely termed ‘Dynamic HTML’ or DHTML– Microsoft and Netscape DHTMLs are different and incompatible,
though both support JavaScript (MS Jscript essentially identical)– Server side scripts are used in the same way as server side
programs, but only for simple operations
Motivation for scripts
• If sophisticated programs (Java, etc.) execute on server only, there are some problems:– Send and receive html from browser, which is treated as dumb
terminal– Not very good interactively: long round-trip delay in displaying
and getting forms with any internal logic or operations– Economic issue (still unsolved): idle clients and expensive,
loaded servers• Solution is to put small programs on client machine to
execute locally (though it hasn’t been a great solution)– Forms with built-in checking, animations, popup window
prompts,… (XML, XForms are better)– Java, JavaScript, VBScript are distinct and confusingly named
languages that address these issues• JavaScript is now considered unsuitable:
– Security issues with loading unknown scripts on browser– JavaScript capabilities limited; can be superseded by server
Browser-server interactionBrowser Side Server Side
• Step 1: Browser requests page without any parameters
• Step 2: Server fetches page, and returns empty input form
• Step 3: User fills out input form and presses ‘submit’ button
• Step 4: Browser packages form into query string and sends to server
• Step 5: Program synthesizes a response document and returns it
Web svrGET /MyApp/MyPage
Web svr
MyProg
MyProg
GET /MyApp/MyProg?name=Pat
xxxxxxxxxxxx
Every dynamic validation, fill-in requires server intervention.- If later choices depend on earlier choices, etc.- JavaScript was felt to be solution, now XML, XSLT are- Pages can be XML or HTML
JavaScript (or VBScript) on browser
• Can read and write parts of their own documents and other documents the browser has open
• Limited access to browser resources (e.g., history list, back and forward buttons)
• Can read and set contents of fill-out forms, open new windows, create new documents (access to local folders!)
• Library of math and text manipulation functions• Limited network communications, graphics and window
creation• Must use Java, not JavaScript, if you need to go beyond the
bounds of an html document or a simple feature, such as: – Animation, simulation, network communications, modules– JavaScript has no modules and gets unwieldy after 300-400
lines• Use server side includes to fake a JavaScript library
– JavaScript code can’t be kept private; Java can be compiled
Common JavaScript applications
• Create ‘forward’ and ‘backward’ buttons using history list– Hard to know how user got to a static html page without
JavaScript• Create menus that select among URLs
– Conserve space by having list boxes instead of text lists• Create scrolling or active headers or marquees
– Use function to shift strings one character at a time using setTimeout()
• Create navigation bars in frames– Allow menu in one frame to control display in another
frame– Extension of menus that select among URLs
• Again, these are simple enough that XML and XSLT can provide these features without downloading ‘active’ content to the browser from a server
JavaScript applications, cont
• Validating fill-out form before submitting it– Routine runs to check for required fields and valid formats– If not correct, display alert box and refuse to submit form
• Creating pick lists for text fields using popup menus
• Creating shopping cart (not the best way to do it, though)– Ecommerce application to add selected items to an order– Frames can be used for short catalogs; windows for long
catalogs– Cookies must be used to maintain current status of cart
• Browsers reload JavaScript every time user resizes windows or frames
• Use local disk storage with cookie
JavaScript shopping cart example
Java applets (on browser)• Java-enabled browsers can download and execute Java
applets (small Java programs)• Java applets are much more powerful than JavaScript
– Open own windows– Create buttons– Create animations on the fly, 3D model views, calculators, etc.– Open network connections to home server, etc.
• Libraries for networks, graphics, multimedia, controls (widgets)
• Platform-independent: UNIX, Windows, Mac, …• Security features (much better than scripts or ActiveX)• However, applets are still very limited because they run on
the browser:– No direct database access, little access to client hardware, less
access to browser internal objects than JavaScript (due to security concerns)
Java applets
• Applets are embedded in HTML documents (like images)– <APPLET>
• Browser examines tag to find location of Java code• Browser downloads code, makes room on page, and
runs it– Usually from same server as HTML but not always
• Applet does the rest:– Draws text, graphics into its space– Interacts with user with its own buttons
• Most applets run in same windows, but some open new one
• Applet runs until user closes browser window or moves to different page
<APPLET> tag<APPLET
CODE= name of applet compiled file (.class file)WIDTH= width of applet (pixels)HEIGHT= height of applet (pixels)CODEBASE= URL of appletALT= alternate text to displayNAME= applet nameALIGN= alignmentVSPACE= extra whitespace above and below appletHSPACE= extra whitespace to left and right of applet
><PARAM NAME=“first parameter” VALUE=“first value”><PARAM NAME= “second parameter” VALUE=“second value”>…HTML text (ignored by applet; displayed by non-Java-
enabled browsers)</APPLET>
Java applet (runs on client, not server)
Java applet HTML
<html> <head><title>Charting Applet</title></head>
<body><h1>Charting Applet</h1><APPLET CODEBASE="./applets" CODE="ChartUI"
WIDTH=400 HEIGHT=300><PARAM NAME="LocationType" VALUE=URL><PARAM NAME="Location"
VALUE="applets/goatdata.txt"><PARAM NAME="Style" VALUE="3D
Pie"></APPLET>
Typical current Java applet examples• Page decorations
– Marquees, banners, etc.• Animation (set of .gif files that are looped through)• Multimedia buttons• Image maps (client side)• Graphics (charts, graphs)• Slide shows• Real applications implemented as applets are rare...
– JavaScript can now pass parameters to applets– Signed applets have more permissions than anonymous
applets– CORBA ORBs allow Java applets still more permissions (next
lecture)• Similar to JavaScript (or VB Script), this has not been
very useful yet
Java on servers• Java servlets. Implement the following steps:
– Read data sent by browser• Usually entered by user, but could be from applet or
JavaScript– Look up other information from the HTTP request
• Browser capabilities, cookies, host, etc. from HTTP headers
– Generate results• Access database, execute program (possibly via
CORBA/COM), etc.– Format the results as an HTML, XML or other
• Servlets can generate GIF, gzip, many MIME types– Set HTTP response parameters in headers– Send document back to browser
• Java Virtual Machine (JVM) runs the servlets on the server
• These evolved from applets (useless) into servlets (extremely useful, secure, standard)
Servlet exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class Hello1264 extends HttpServlet {public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");PrintWriter out = response.getWriter();String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +"Transitional//EN\">\n";
out.println(docType +"<HTML>\n" +"<HEAD><TITLE>Hello 1.264</TITLE></HEAD>\n" +"<BODY>\n" +"<H1>Hello 1.264</H1>\n" +"</BODY></HTML>");}}
Java Server Pages (JSP)
• Allows us to mix static HTML with dynamically generated content from servlets– Many Web pages are primarily static– Changeable parts are in only a few locations on the page
• A servlet requires us to generate the entire page dynamically each time
• JSP allows the Web designer to write static HTML and leave stubs for dynamic content
• Java programmers can then write the stubs• Active Server Pages is very similar (homework 6)
– You won’t need to write any code!
JSP example<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"><HTML> <HEAD><TITLE>JSP Example</TITLE><LINK REL=STYLESHEET
HREF="JSP-Styles.css"TYPE="text/css">
</HEAD><BODY><H2>JSP Expressions</H2><UL><LI>Current time: <%= new java.util.Date() %><LI>Your hostname: <%= request.getRemoteHost() %><LI>Your session ID: <%= session.getId() %><LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %></UL></BODY></HTML>
JSP Example 2<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD> <TITLE>Color Testing</TITLE> </HEAD><%String bgColor = request.getParameter("bgColor");boolean hasExplicitColor;if (bgColor != null) {hasExplicitColor = true;
} else {hasExplicitColor = false;bgColor = "WHITE";}
%>
JSP Example 2, cont.
<BODY BGCOLOR="<%= bgColor %>"><H2 ALIGN="CENTER">Color Testing</H2><%if (hasExplicitColor) {out.println("You supplied an explicit background color of " +bgColor + ".");
} else {out.println("Using default background color of WHITE. " +
"Supply the bgColor request attribute to try " +"a standard color, an RRGGBB value, or to see " +"if your browser supports X11 color names.");
}%></BODY></HTML>
Example Active Server Page or ServerSideJavaScript page
<HTML><HEAD>… ‘Normal HTML page sections</HEAD><BODY>
<% … %> ‘Script that runs on server as pg created<SCRIPT LANGUAGE=“JavaScript”>… ‘Script that runs in browser as pg interpreted</SCRIPT><SERVER>… ‘Script executed on server, as pg created</SERVER><!--#include … --!> ‘Server-side include, e.g., script or
‘HTML stored in files<TABLE> ‘Normal HTML code...</TABLE>
</BODY></HTML>
Coordinating scripts on server and client
• Browsers support VBScript, JavaScript and Java (JVM)– Server may execute some scripts or programs on its
own machine, and return others to the browser for execution on the client
– Java applets, client side JavaScript and ActiveX controls are always executed on client:
• Applets are sent between <APPLET> and </APPLET> tags• ActiveX controls are sent between <OBJECT> and
</OBJECT> tags• JavaScript is sent between <SCRIPT> and </SCRIPT> tags
– Scripts to be executed on server:• <% … %> or <SERVER> encloses scripts to be run on
server– This code executes as page is being generated/interpreted on
server
JavaBeans• Component model for Java servlets and Java Server
Pages– Support reusable application components– Components are pre-developed pieces of application code
that can be assembled and integrated into working applications
– Beans are encapsulated classes whose code cannot be changed
• All data (properties) have SetXxx and GetXxx methods• This allows a visual Properties box to display and set all data• (Beans also need a 0-argument constructor and have no public
data)– Beans are usually used in Java Server Pages, which offer
the best ‘component environment’
Enterprise Java Beans (EJBs)
HTTPserver
Servlet,JSP
Sessionobject
Entityobject
EJB server/container
Web server/container
Web client
Database
EJBs, cont
• Session beans– Represents client (browser), always a single client– Keeps ‘state’: the status and current representation of the
session (or can be stateless)– Creates session bean ‘just in time’ when needed, for efficiency
and load balancing• Entity beans
– Representations of back end data: a database, almost always– Persistent, represent one object (often a table)– Manages transactions, including rollbacks if failures
• Two phase commit, just as databases use• Both EJBs are highly reusable and portable
– Sharply reduce programming effort– Can be attached, configured in many ways by non-
programmers
Summary: Java (J2EE) environment
Applicationserver
Applicationserver
LinuxWindowsOther
Java virtual machine
HTML, XMLJava RMI, XML
EJBs
Webserver
XML databases
Java virtual machine
Active Server Pages Architecture
InternetInformation
Server(IIS)
CGIInternet
Perl, Awk
Server-sideincludesActive Server Pages (DLLs)
VB Script J Script ADO ODBCASPcomponents
DataActive Server Pages (.ASP files)