Servlet - The Toppers Way

advertisement
WEB TECHNOLOGY
THETOPPERSWAY.COM
UNIT-4 SERVER SIDE PROGRAMMING
CGI
SERVLET
JSP
ASP
ASP.NET
COM / DCOM
Server-side programming
 In many cases, client-side applications will
be insufficient
Heavy processing
 Communication with other clients
 Data available on server-side only

 It may be useful to send the request to the
server, and to process it there.
 A number of technologies available: CGI,
Servlets, JSP, ASP, PHP and others
 We will look at CGI, Servlets and JSP.
Static Pages
Request file
Retrieve file
Send file
Dynamic Pages
Request service
Do Computation
Generate HTML
page with results
of computation
Return dynamically
generated HTML file
CGI programming
Common Gateway Interface (CGI)
 CGI stands for Common Gateway Interface
 CGI is a standard programming interface to
Web servers that allows building dynamic and
interactive Web sites
 CGI is not a programming language.
It is just a set of standards (protocols)
 The standards specify how Web-applications can be
executed on the server-side

CGI Cont..
 CGI can be implemented
 in an interpreted language such as PERL
 in a compiled language such as C
 Any program can be converted to a CGI
program

It just has to follow the CGI rules
 The rules define
 How programs get and sends data (i.e.,
communication protocol)
 How to make sure Web server knows that a program
is a CGI program.
CGI Cont..
 A CGI program is
 Stored on the server,
 Executed on the server,
 Executed in response to request from client.
 By running a CGI program, rather than
delivering a static HTML page, the server can:
Put dynamic and updated information on web page
(e.g., weather forecast, stocks price, product
availability, etc…).
 Respond appropriately to user input.
 Store user data on server-side in a file or DB.

Dynamic Pages Using CGI
Request service
Run CGI program
…
…
…
print $result
Return dynamically
generated HTML file
<HEADER>
<BODY
</BODY>
Calling CGI Program
 CGI program can be called in the same way
that static HTML pages.

For example, a link that when clicked, will run CGI
program on the server-side
<a href=“http://www.mysite/cgi-bin/myprog”>
Run my CGI program </a>
 It can be invoked by a form
<form action=“cgi-prog.cgi” method=“POST”>
. . .
</form>
 CGI programs are usually executed as
processes
How does it know its CGI?
 How does the Web server know whether the
request deals with static HTML page, or with
invoking a CGI program?
The Web server is configured in a way that provides
clear distinction between HTML and CGI files.
 Unix servers usually put the CGI programs in a
cgi-bin directory.

 Access permissions are restricted, such that
writing to this directory is allowed to superusers, while executing is allowed to
everybody.
CGI invocation
 HTTP GET request:
GET /webp/cgi-bin/printenv.pl HTTP/1.0
 Looks like standard HTTP request, but actually
will not return printenv.pl file, but rather the
output of running it.
 Different behaviors:
regular directory => returns the file
 cgi-bin => returns output of the program

 The behavior is determined by the server
 E.g., if the path is cgi-bin, pass to CGI handler
CGI Input Data
 Input parameters can be passed to a CGI
program
 For example, HTML forms wrap and encode the
form fields as a string looking like:
var1=val1&var2=val2&var3=val3&…
 This string is concatenated to the CGI URL, after
the ? character
 Example: GET /webp/cgi-bin/printenv.pl?
var1=val1&var2=val2&var3=val3
 The parameters can be extracted by the CGI
through environment variables
GET vs. POST
 Above examples used the GET method to handle
the data from the form.
 The form data was concatenated to the CGI URL
 In the POST method the data is sent to the CGI
separately, in the request body.
 GET method is not secure, the data is visible in
URL.
 GET is suitable for small amounts of data
(limited to 1K), but not for larger amounts.
 What about refreshing in GET and POST?
Security issues with CGI
 Publicly accessible CGI program allows anyone
to run a program on the server.
 Malicious users may be able to exploit security
breaches, and harm to the server.
 Because of this many Web hosts do not let
ordinary users create CGI programs.

Where the use of CGI, is permitted special wrapper
programs may be required that enhance security
checks and to limit the CGI program permissions.
CGI Summary
 CGI is a standard for interfacing Web client to




the programs running on server-side.
Specifies location of files (so server knows to
execute them!) and how input data is handled.
The output is displayed according to it.
Simple examples using shell script, but need
more serious language for complex ones.
Security breaches of CGI should be handled
Servlets vs. CGI
 Servlet – Java-based CGI
 Executed by servlets container
 Golden goals: "performance, flexibility,
portability, simplicity and security"
 Faster and thinner
No fork-process execution like Perl
 No need to initialize for each request
 Only lightweight thread context switching
 Built-in multithreading

Java Servlets
Java Servlet
 Servlets are generic extensions to Java-enabled
servers
 Servlets are secure, portable, and easy to use
replacement for CGI
 Servlet is a dynamically loaded module
that services requests from a Web server
 Servlets are executed within the Java Virtual
Machine
 Because the servlet is running on the server side, it
does not depend on browser compatibility
Advantages of Servlets
 Efficiency
 More efficient – uses lightweight java threads as opposed to
individual processes
 Persistency
 Servlets remain in memory
 Servlets can maintain state between requests
 Portability
 Since servlets are written in Java, they are platform
independent
 Robustness
 Error handling, Garbage collector to prevent problems with
memory leaks
 Large class library – network, file, database, distributed object
components, security, etc.
Advantages of Servlets
 Extensibility
 Creating new subclasses that suite your needs

Inheritance, polymorphism, etc.
 Security
 Security provided by the server as well as the Java Security
Manager
 Eliminates problems associated with executing cgi scripts using
operating system “shells”
 Powerful
 Servlets can directly talk to web server
 Facilitates database connection pooling, session tracking etc.
 Convenient
 Parsing and decoding HTML form data, reading and setting HTTP
headers, handling cookies, etc.
A Servlet’s Job
 Read explicit data sent by client (form data)
 Read implicit data sent by client
(request headers)
 Generate the results
 Send the explicit data back to client (HTML)
 Send the implicit data to client
(status codes and response headers)
Execution of Java Servlet
Web
Browser
Web
Server
Request
Servlet
Response
 Applications of Java Servlets
 Building e-commerce store fronts
Servlet builds an online catalog based on the contents of a
database
 Customer places an order, which is processed by another
servlet



Servlets as wrappers for legacy systems
Servlets interacting with EJB applications
Java Servlet Alternatives
 CGI – Common Gateway Interface
 New process for every cgi request
Slow response time
 If cgi program terminates before responding to web server, the
browser just waits for a response until it times out

 Proprietary APIs
 NSAPI – Netscape Server API
 ISAPI – IIS Server API

Dynamic link libraries
 Server-Side JavaScript
 Embedding javascript into precompiled HTML pages –
only few servers support it
Java Servlet Architecture
 Two packages make up the servlet architecture
 javax.servlet


Contains generic interfaces and classes that are implemented
and extended by all servlets
javax.servlet.http

Contains classes that are extended when creating HTTPspecific servlets
 The heart of servlet architecture is the interface
class javax.servlet.Servlet
 It provides the framework for all servlets
 Defines five basic methods – init, service, destroy,
getServletConfig and getServletInfo
GenericServlet & HttpServlet
 HttpServlet class is extended from GenericServlet
class
 GenericServlet.service() method has been defined
as an abstract method
 The two objects that the service() method receives
are ServletRequest and ServletResponse
 ServletRequest Object

Holds information that is being sent to the servlet
 ServletResponse Object
 Holds data that is being sent back to the client
GenericServlet & HttpServlet
 Unlike the GenericServlet, when extending
HttpServlet, don’t have to implement the service()
method. It is already implemented for you
 When HttpServlet.service( ) is invoked, it calls
doGet( ) or doPost( ), depending upon how data is
sent from the client
 HttpServletRequest and HttpServletResponse
classes are just extensions of ServletRequest and
ServletResponse with HTTP-specific information
stored in them
Servlets vs. CGI
 Multi-threaded execution allows to:
 share data across successive requests
 share data between concurrent requests
 use hidden fields, cookies, or sessions
 Java supports “write once, run anywhere” paradigm
 Easier than unportable Perl
 Java provides enhanced security
 Supports all HTTP request methods
 GET, POST, PUT, DELETE, and others
Servlet Architecture: 3-Tier system
 Tier 1: Client
 HTML browser
 Java client
 Tier 2: Servlets
 embody business logic
 secure, robust
 Tier 3: Data Sources
 Java can talk to SQL, JDBC, OODB, files, etc…
Web Application model
Client Tier
Middle Tier
Enterprise Information
System (EIS) Tier
SQL
application
browser
Web Container
Servlet
Servlet
JSP
…
Database
File
system
Servlet Name
 Servlet is invoked using his name
 Servlet should be located in appropriate directory
 A servlet’s name is its class name
 Name is usually a single word
 Possibly with a package name and dots
 Standard names: DateServlet (echoes current
date/time), EchoServlet (bounces back CGI
parameters), and many others
 Refer the server documentation
Servlet Invocation
 Can be invoked directly using the <servlet>
tag
pass servlet parameters in param tags
 codebase of the servlet can be specified

<servlet code=DateServlet.class
codebase=http://servlets.foo.com/>
<param name=serviceParam1 value=val3>
<param name=serviceParam2 value=val4>
</servlet>
 Typically invoked by form’s action attribute
The Servlet API
 Defined in javax.servlet package
 Independent of
 Web protocol
 server brand or platform
 whether it is local or remote servlet
 Provides core servlet functionality
 just extend it
 CGI-like functionality
 generic interface
 accepts query, returns response
The Servlet API
 javax.servlet
 Basic servlet API definitions.
 What are the inputs and outputs to/from Servlet
 Not tied to any specific protocol (e.g., HTTP)
 These low-level classes/interfaces usually are not
used
 javax.servlet.http
 HTTP-related definitions
 Extension of the basic interfaces to handle the
HTTP protocol functionality
 This package will be heavily used
Servlet Architecture Overview
Servlet
GenericServlet
 Servlet Interface
 methods to manage servlet
 GenericServlet
 implements Servlet
 HttpServlet
 extends GenericServlet
 exposes HTTP-specific
functionality
Interface
Clas
s
HttpServlet
implements
extends
doGet()
doPost()
service()
...
Clas
s
UserServlet
extends
Class
Class
Override one or more of:
doGet()
doPost()
service()
...
Servlet Architecture Overview
 ServletRequest
 Request sent by the client to the server
 ServletResponse
 Response sent by the server to the client
 Is being sent only after processing the request
 HttpServletRequest, HttpServletResponse
 HTTP-specific request and response
 In addition to the regular request and response, tracking
client information and manages the session
The HelloWorld Servlet
import javax.servlet.*;
import java.io.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest req,
ServletResponse res) throws IOException,
ServletException{
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println("Hello, World!");
}
}
Servlet Lifecycle Overview
 Server loads and instantiates servlet
 Server calls init() method
 Loop
 Server receives request from client
 Server calls service() method
 service() calls doGet() or doPost() methods
 Server calls destroy() method
 More detail to come later...
Servlet interface
 Central abstraction in the Servlet API
 All servlets implement this interface
 Either directly, or
 By extending another class that implements it
 Defines abstract methods for managing the
servlet and its communications with clients
 Servlet writers provide these methods
While developing servlets
 Implementing the interface

Servlet classes
 GenericServlet class
 implements Servlet
 also implements Serializable, ServletConfig
 implements all Servlet methods
 HttpServlet class
 extends the GenericServlet class
 provides a framework for handling the HTTP
protocol
 has its own subclasses of ServletRequest and
ServletResponse that do HTTP things
HttpServlet methods
 HTTPServlet class provides helper methods for
handling HTTP requests
doGet (GET and HEAD)
 doPost (POST)
 doPut, doDelete (rare)
 doTrace, doOptions (not overridden)

 The service() method dispatches the requests to the
appropriate do* methods
Generic Servlet vs. HTTP Servlet
GenericServlet
Client
request
Server
service ( )
response
HTTPServlet
Browser
doGet ( )
request
HTTP
Server
response
service ( )
doPost ( )
ServletRequest class
 Encapsulates the clientserver
communication
 Allows the Servlet access to
Names of the parameters passed in by the client
 The protocol being used by the client
 The names of the remote host that made the request
and the server that received it
 The input stream, ServletInputStream, through
which the servlet gets data from clients

 Subclasses of ServletRequest allow the servlet
to retrieve more protocol-specific data

HttpServletRequest for accessing HTTP-specific
header information
ServletRequest - Client Info
 getRemoteAddr()
 Returns the IP address of the client that sent the request
 getRemoteHost()
 Returns the fully qualified host name of the client that sent
the request
 getProtocol()
 Returns the protocol and version of the request as a string
<protocol>/<major version>.<minor version>.
ServletRequest - URL Info
 getScheme()
 Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".
 getServerName()
 Returns the host name of the server receiving the
request
 getServerPort()
 Returns the port number on which this request was
received
 getServletPath()
 Returns
the URL path that got to this script, e.g.
“/servlet/com.foo.MyServlet”
 Useful for putting in a <FORM> tag
ServletRequest - Contents
 getContentLength()
 Returns the size of the request data
 getContentType()
 Returns the MIME type of the request data
 getInputStream()
 Returns an input stream for reading binary data in
the request body.
 getReader()
 Returns a buffered reader for reading the request
body.
ServletRequest - Parameters
 String getParameter(String)
 Returns a string containing one value of the specified
parameter, or null if the parameter does not exist.
 String[] getParameterValues(String)
 Returns the values of the specified parameter as an
array of strings, or null if the named parameter does
not exist.
 Useful for parameters with multiple values, like lists
 Enumeration getParameterNames()
 Returns the parameter names as an enumeration of
strings, or an empty enumeration if there are no
parameters or the input stream is empty.
ServletResponse class
 Encapsulates the serverclient
communication
Gives the servlet methods for replying to the client
 Allows the servlet to set the content length and
MIME type of the reply
 Provides an output stream, ServletOutputStream
through which the servlet can send the reply data

 Subclasses of ServletResponse give the servlet
more protocol-specific capabilities.

HttpServletResponse for manipulating HTTPspecific header information
ServletResponse
 Embodies the response
 Basic use:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML><BODY>Hello</BODY></HTML>");
 setContentType() is usually called before calling
getWriter() or getOutputStream()
ServletResponse - Output
 getWriter()
 for writing text data
 getOutputStream()
 for writing binary data
 or for writing multipart MIME
 And many other methods, similarly to the methods
of ServletRequest
 Refer the documentation
Servlet Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Servlets are not part of the standard SDK,
they are part of the J2EE
Servlets normally extend HttpServlet
public class ServWelcome extends HttpServlet
The response to be sent to the client
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
Details of the HTTP request from the client
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Set the response type to text/html (this is
normal)
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet Program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>");
Do not forget to close the
out.close();
This HTML text is
connection
with
the
client
}
sent to the client
}
Compiling and Invoking Servlets
 Set your CLASSPATH
 Servlet JAR file (e.g.,
install_dir\lib\common\servlet.jar).
 Top of your package hierarchy
 Put your servlet classes in proper location
 Locations vary from server to server. E.g.,
tomcat_install_dir\webapps\examples\WEB-INF\classes
 jrun_install_dir\servers\default\default-app\WEB-INF\classes

Invoke your servlets
 http://host/servlet/ServletName
 Custom URL-to-servlet mapping (via web.xml)

Date Servlet Example
public class DateServlet extends HttpServlet {
public void service(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
Date today = new Date();
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println(today.toString());
}
public String getServletInfo() {
return "Returns a string representation of the
current time";
}
}
Hello Servlet
public class HelloHttpServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException{
String name = req.getParameter("name");
if (name == null) name = “guest";
res.setContentType("text/plain");
ServletOutputStream out =
res.getOutputStream();
out.println("Hello, " + name + "!");
}
}
Hello Servlet
 Reads in a single input parameter
 Can be used from a form
<FORM METHOD=GET
ACTION=”/servlet/HelloHttpServlet”>
<INPUT NAME=name>
</FORM>
 Can use right in a URL
http://localhost/servlet/HelloHttpServlet?
name=Fred
 Generates HTML output
Servlet Lifecycle: init()
 public void init(ServerConfig cfg)
 Is called only once
 when servlet loads
 upon clients request
 Do not worry about synchronization
 Perform costly setup here, rather than for each
request
open database connection
 load in persistent data
 spawn background threads

init() details
 init() should be completed before starting to handle
requests
 If init() fails, UnavailableException is thrown
 Invocation process allows to look-up for the
initialization parameters from a configuration file

getInitParameter(paramName) method is used to read the
parameters

init() parameters are set by the administrator
servlet parameters are set by the invocation

Servlet Lifecycle: service()
 After the service loads and initializes the
servlet, the servlet is able to handle client
requests
 public void service(ServletRequest req,
ServletResponse res)
takes Request and Response objects
 called many times, once per request

 Each request calls the service() method
 service() receives the client's request, invokes
appropriate handling method (doPost(), doGet()
etc…) and sends the response to the client
service() and concurrency
 Servlets can run multiple instances of service()
method concurrently
service() must be written in a thread-safe manner
 it is developer’s responsibility to handle synchronized
access to shared resources

 It is possible to declare a servlet as single-
threaded
implement SingleThreadModel (empty) interface
 guarantees that no two threads will execute the
service() method concurrently
 performance will suffer as multiple simultaneous can
not be processed

Servlet Lifecycle: destroy()
 Servlets run until they are removed
 When a servlet is removed, it runs the destroy()
method
 The destroy() method is run only once

the servlet will not run again unless it is reinitialized
 public void destroy()
 takes no parameters
 afterwards, servlet may be garbage collected
Servlet Lifecycle: destroy() details
 Releasing the resources is the developer’s
responsibility


close database connections
stop threads
 Other threads might be running service requests, so
be sure to synchronize, and/or wait for them to quit
 Destroy can not throw an exception

use server-side logging with meaningful message to
identify the problem
Technical details
 getServletInfo() method overrides the method
inherited from Servlet class

Returns a string containing information about the
servlet: author, version, etc…
 Servlet can be dynamically reloaded by the
server at the run-time
HttpServlet.getLastModified returns the time the
servlet was last modified
 Improves performance on browser/proxy caching

 Debugging servlets through printing to HTML
Scalability of servlets
 The servlet is only recompiled if it was
changed otherwise the already compiled class
is loaded

Faster response times because the servlet does not
need to be recompiled
 The servlet can be kept in memory for a long
time to service many sequential requests

Faster response times because the servlet does not
need to be reloaded
 Only one copy of the servlet is held in memory
even if there are multiple concurrent requests

Less memory usage for concurrent requests and no
need to load another copy of the servlet and create a
new process to run it.
Java Server Pages
Java Server Pages – JSP
 Java Servlets can be awkward to use.
 Servlets often consist mostly of statements to write out
HTML (with just a few dynamic calculations, database
access etc…).
 It may be difficult to write servlets to produce attractive
well “styled” pages.
 JSP allows to mix standard static HTML pages
with dynamically generated HTML.
 Hybrid of HTML and servlets
Java Server Pages – JSP
 JSP technically can not do anything that
servlets can not do
 Following example illustrates how we to get
JSP code embedded in the HTML
<html>
<head> … </head>
<body>
<h1> Todays date is:</h1>
<%= new java.util.Date() %>
</body>
</html>
Java Server Pages – JSP
 JSPs execute as part of a Web server by special
JSP container
 Basically, on first access to JSP code
it is automatically converted into servlet code
 stored as servlets on the server
 will be invoked on fouture requests

 Notice the “first invocation delay”
 JSP errors
 Translation-time errors - occur when JSP is
translated into servlets
 Request-time errors - occur during request
processing
JSP vs. Servlets
 JSP
 Look like standard HTML
Normally include HTML markup tags
 HTML codes can be written easily


Used when content is mostly fixed-template data

Small amounts of content generated dynamically
 Servlets
 HTML codes have to be written to the PrintWriter or
OutputStream
 Used when small amount of content is fixed-template
data

Most content generated dynamically
JSP page translation and processing phases
Translation phase
Hello.jsp
Read
Request
helloServlet.java
Generate
Client
Response
Server
Execute
69
helloServlet.class
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Processing phase
A simple example
Java Servlet & JSP
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
<HTML> res)
public void doGet(HttpServletRequest req, HttpServletResponse
throws ServletException, IOException {
res.setContentType("text/html");
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
PrintWriter out = res.getWriter();
<BODY>
<H1>
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
<%
out.println("<BODY>");
if (request.getParameter("name") == null)
{
out.println("<BIG>Hello World</BIG>");
out.println("Hello World");
out.println("</BODY></HTML>");
} else {
}
out.println("Hello, " + request.getParameter("name"));
}
}
%>
</H1>
All copyrights reserved
</BODY>
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
</HTML>
70
out.println("<HTML>");
Template Pages
Server Page Template
Resulting HTML
<html>
<html>
<title>
<title>
A simple example
A simple example
</title>
translation </title>
<body color=“#FFFFFF”>
<body color=“#FFFFFF”>
The time now is
The time now is
<%= new java.util.Date() %>
Tue Nov 5 16:15:11 PST 2002
</body>
</body>
</html>
All copyrights reserved
CSC1720
Introduction
to Internet
</html>
by–C.C.
Cheung 2003.
71
Tomcat
 Tomcat is the Servlet Engine than handles
servlet requests for Apache application server
It is best to think of Tomcat as a “servlet container”
 Tomcat can handle Web pages, Servlets, and JSPs

 Apache can handle many types of Web services
 Apache can be installed without Tomcat
 Tomcat can be installed without Apache
 It is easier to install Tomcat standalone than as
part of Apache
 Apache and Tomcat are open source (free)
 One of the coming classes will focus on Tomcat
Advantages of Tomcat
 1) It is an open source application server
 2) It is a light weight server (no EJB)
 3) It is easily configured with apache and IIS
 4) Very stable on Unix systems
 5) Good documentation online
 6) Java Sun compliant
 7) Does not require a lot of memory at startup
 8) It is free, yet high quality!
73
Which Should I Use? Client- or Server-Side?
 If you want to have dynamic client forms with
client-side validation, you must use client-side
programming.
 If you want your site to have highly interactive
pages, you should use client-side programming.
 If you need to provide your client with advanced
functionality that can be created only using
ActiveX controls (or Flash, or …), you must use
client-side programming.
Which Should I Use? Client- or Server-Side?
 If you want to control the user's browser (i.e., to
turn off the menus or place the browser in kiosk
mode), you must use client-side programming.
 If your Web site must work with every browser on
the market, and you do not want to create several
different versions for different browsers, you
should avoid client-side programming.
 If you want to protect your source code, you must
use only server-side programming. Client-side
source code is transferred to the browser.
Which Should I Use? Client- or Server-Side?
 If you need to track user information across several
Web pages to create a "Web application“, you must
use server-side programming.
 If you need to interact with server-side databases,
you must use server-side programming.
 If you need to use server variables or check the
capabilities of the user's browser, you must use
server-side programming.
JSP elements
 A JSP is a template for generating a web page
 Response to an http request
 JSP elements are tags embedded in HTML
 JSP scripting elements
 Specify Java code to be run when template is requested
 Separate the coding from HTML content

Fits with M-V-C philosophy
Simple JSP Example
<HTML>
<HEAD>
<TITLE>JSP Digital Clock</TITLE>
</HEAD>
<BODY>
<H1>Date and Time</H1>
<!--table in here-->
<%= new java.util.Date.toString() %>
<!-- end table-->
</BODY>
</HTML>
JSP scripting elements
 Three different kinds of scripting,
determining when each is executed:
 Insert snippets of Java code
<% … %>
 embed a code expression, which evaluates in
the response (no ;)
<%= … %>
 declare variables and methods
<%! … %>
Examples
<!--Declare a variable-->
<%! String name = “Gandalf”; %>
<!-- Do some processing-->
<% name = name + “ the Grey”;%>
<!-- Output a result-->
<h1><%= name %></h1>
result
JSP directive elements
 applied when the JSP is compiled into a servelet
 Only executed once (on compilation)
 Do not affect the response
 Used to set up resources such as
 Java classes
 inclusions
JSP directive elements
 specify page information (static)
<%@ page … >
scripting language, error page
<%@ include … >
includes a file, e.g. an applet
<%@ taglib … >
declare a tag library (custom actions)
JSP and http
JSP and http
 A JSP is a servelet
 Permanently resident in server memory
 Multi-threaded
 Request and response objects
 Sessions and cookies
Accessing request information
 Methods of the request object provide all request
information
 object is called “request”
public String getParameter (String name)
public String getMethod ()
public String getHeader (String name)
public Cookie [] getCookies ()
javax.servelet.http.Cookie class
 getName ()
 the name of the cookie
 getValue(), setValue (String value)
 gets/sets the value of a cookie
 getDomain(), setDomain(String dName)
 get/set the cookie domain name
 getPath(), String setPath(String path)
 get/set the request path the cookie is associated with
 getMaxAge(), setMaxAge (int expiry)
 get/set maximum age for the cookie
javax.servelet.http.HttpSession
 provides standard functionality for handling
sessions
 handles cookies as standard but must be
extended to handle URL rewriting
 holds client state info resident in memory

automatically times out abandoned sessions
 created/returned by HttpServeletRequest class
getSession method
JSP and Java Beans
Java Beans
 ordinary Java classes with the following properties:
 introspection
 customization
 events
 properties
 persistence
Java Beans
 introspection
 an analyser can inspect how the Bean works
 properties
 naming conventions for getter and setter methods
 persistence
 implement the Serializable interface
 Bean state can be stored
Example Java bean
public class ExampleBean implements
java.io.Serializable {
private String name = null;
private int score = 0;
public ExampleBean() {} // Empty constructor
/* Getter and Setter Methods */
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
Example Java bean
public int getScore() {
return score;
}
public void setScore(int i) {
score = i;
}
/*
No method required to implement
Serializable
*/
}
JSP action elements
 action elements
 perform an action when page is requested
<jsp:useBean>
uses a JavaBean component
<jsp:getProperty>
property from JavaBean used in the page
<jsp:setProperty>
sets a JavaBean property (possibly using
request information)
Other JSP action elements
<jsp:include>
responses from other jsp pages or servelets
<jsp:forward>
forwards processing to other jsp or servelet
<jsp:param>
passes a parameter with include or forward
<jsp:plugin>
generates the HTML to embed an applet
Java 2, Standard Edition
Source:
java.sun.com
97
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Java 2 Platforms
98
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Web Services
 What are Web services?
 They are a distributed computing architecture.
 Who is using Web services now?
 Industry technologies
 Which approach should we use - .NET or J2EE?
 Requestor, Registry, Provider
99
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Critical Elements of a Basic Web Services
Architecture
Format
XML (Format)
For presenting data and information
Services UDDI (Publish) WSDL (Find) SOAP (Bind)
A directory service
A protocol for
applications to find
a service
Network
A protocol that
enables applications
to agree the
communication
The Internet
The Internet, using TCP/IP protocols…
100
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Service-Oriented Architecture
Find - UDDI
Requestor
Registry
Bind –
WSDL, SOAP
Publish - UDDI
Provider
101
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Background
Web Architecture
PC/Mac/Unix/...
+ Browser
Client
Request:
http://www.digimon.com/default.asp
Network
HTTP, TCP/IP
Response:
<html>….</html>
Server
Web Server
Background
Web Development Technologies
 Client-side technologies
 HTML, DHTML, JavaScript
 Server-side technologies
 ASP (Active Server Pages)
 ASP.NET is the next generation of ASP
Background
What is ASP?
 Server-side programming technology
 Consists of static HTML interspersed with script
 ASP intrinsic objects (Request, Response, Server,




Application, Session) provide services
Commonly uses ADO to interact with databases
Application and session variables
Application and session begin/end events
ASP manages threads, database connections, ...
Background
What is ASP?
HTTP request
HTTP response
(form data, HTTP
header data)
HTML, XML
ASP page
(static HTML,
server-side logic)
Background
Demo: HelloWorld.asp
<html>
<head><title>HelloWorld.asp</title></head>
<body>
<form method=“post">
<input type="submit" id=button1 name=button1 value="Push Me" />
<%
if (Request.Form("button1") <> "") then
Response.Write("<p>Hello, the time is " & Now())
end if
%>
</form>
</body>
</html>
JSP vs. ASP
ASP Technology
JSP Technology
Web Server
IIS or Personal Web Server
Any Web Server
Platforms
Microsoft Windows
Most popular platforms
Reusable
components
No
JavaBeans, JSP tags
Security against
System crashes
No
Yes
Scripting
Language
VBScript, Jscript
Java
 JSP is platform and server independent.
 ASP relies on Microsoft Platforms and All
Servers.
copyrights reserved
107
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
ASP & JSP
<html>
<head><title>Hello World by ASP</title></head>
<body>
<font size=12>
<%
response.write “Hello INE2720 Students and the World!"
%>
</font>
</body>
<html>
<head><title>Hello World by JSP</title></head>
<body>
<font size=12>
<%
out.println("Hello INE2720 Students and the World!");
%>
</font>
</body>
108
All copyrights reserved
CSC1720
Introduction
to Internet
by–C.C.
Cheung 2003.
Background
ASP Successes
 Simple procedural programming model
 Access to COM components
 ActiveX Data Objects (ADO)
 File System Object
 Custom components
 Script-based: no compiling, just edit, save & run
 VBScript, JScript – leverages existing skills
 Support for multiple scripting languages
 ASP has been very popular
Background
ASP Challenges
 Coding overhead (too much code)
 Everything requires writing code!
 Code readability (too complex; code and UI intermingled)
 Maintaining page state requires more code
 Reuse is difficult
 Supporting many types of browsers is difficult
 Deployment issues (e.g. DLL locking)
 Session state scalability and availability
 Limited support for caching, tracing, debugging, etc.
 Performance and safety limitations of script
ASP.NET Overview
 ASP.NET provides services to allow the creation,
deployment, and execution of
Web Applications and Web Services
 Like ASP, ASP.NET is a server-side technology
 Web Applications are built using Web Forms
 Web Forms are designed to make building
web-based applications as easy as building Visual
Basic applications
ASP.NET Overview
Goals
 Keep the good parts of ASP and improve the rest
 Simplify: less code, easier to create and maintain
 Multiple, compiled languages
 Fast
 Scalable
 Manageable
 Available
 Customizable and extensible
 Secure
 Tool support
ASP.NET Overview
Key Features
 Web Forms
 Web Services
 Built on .NET Framework
 Simple programming





model
Maintains page state
Multibrowser support
XCOPY deployment
XML configuration
Complete object model









Session management
Caching
Debugging
Extensibility
Separation of code and UI
Security
ASPX, ASP side by side
Simplified form validation
Cookieless sessions
ASP.NET Overview
Demo: HelloWorld.aspx
<%@ Page Language="VB" %>
<html>
<head>
<script runat="server">
sub B_Click (sender as object, e as System.EventArgs )
Label1.Text = "Hello, the time is " & DateTime.Now
end sub
</script>
</head>
<body>
<form method="post" runat="server">
<asp:Button onclick="B_Click" Text="Push Me"
runat="server" /> <p>
<asp:Label id=Label1 runat="server" />
</form>
</body>
</html>
ASP.NET Overview
Architecture
 ASP.NET is built upon
 .NET Framework
 Internet Information Server (IIS)
ASP.NET Overview
Architecture
VB
C++
C#
JScript
…
ASP.NET: Web Services
and Web Forms
Windows
Forms
ADO.NET: Data and XML
Base Classes
Common Language Runtime
Visual Studio.NET
Common Language Specification
Introduction :
walking towards COM
117
1/2
Windows purpose : moving integration between
applicative functions to O.S. level
 it needs effective communication mechanisms between
applications
COM
OLE
DDE
clipboard
Introduction :
walking towards COM
2/2
118
DLLs are a good starting point for modularity
problems :
• physical location dependency
• version management
we need a better communication mechanism. An object-based and
synchronous client-server technology facilitates:
• robustness
• API’s homogeneity
• physical location independency
• splitting into components
Introducing COM
119
• COM : Component Object Model (1992)
 component software architecture that allows
applications and systems to be built from components
supplied by different software vendors
supports : interoperability and reusability
benefits : maintainability and adaptability
however, in order to interact, components must adhere to a binary
structure specified by Microsoft
Component Object Library
120
A system component that provides the mechanics of
COM:
• provides the ability to make IUnknown calls across processes
• encapsulates all the “legwork” associated with launching
components and establishing connections between
components
Creating a component
object
Application
CLSID
.EXE
Component
Object
Library
CLSID
Registration
DB
CLSID
DLL
121
COM server
122
In general :
some piece of code that implements some
component object such that the Component Object
Library and its services can run that code and have
it create component objects
Three ways in which a client can access COM objects provided
by a server:
• In-Process Server
• Local Object Proxy
• Remote Object Proxy
Client
Process
Local Server Process
In-Process
Object
Local
Object
Stub
Cient
Application
In-Process
Server
RPC
Local
Object
Proxy
COM
Remote
Object
Proxy
COM
Local
Server
Remote Machine
Remote Server Process
RPC
123
Stub
Remote
Object
COM
Remote
Server
COM object
124
In general :
some function that produces a defined output, given tah the
input meets predefined parameters.
COM encapsulates the function, only giving the client of an
object acces to the object interface(s).
All COM objects :
• are registered with a component database
• have no identity
Client
Application
4) Call interface
members
Object
3) Get object interface
pointer return to client
Server
2) Locate
Implementation
1) Create
Object
COM
What happens when a client wishes to create and use a COM object?
125
COM Technologies
126
Interfaces and API functions that expose operating
system services, as well as other mechanisms necessary
for a distributed environment :
 Type Information
 Structured Storage and Persistence
 Monikers
 Uniform Data Transfer
 Connectable Objects
Introducing DCOM
127
An extension to COM that allows network-based component
interaction
COM : processes can run on the same machine but in different
address spaces
DCOM extension : allows processes to be spread across a network
DCOM (1995) is a seamless evolution of COM
 you can take advantage of your existing investment in COM-based
applications, components, tools and knowledge
DCOM Architecture
COM
Object
Component
Security
Provider
DCE RPC
Protocol Stack
128
Component
COM
Object
Security
Provider
DCE RPC
Protocol Stack
DCOM networkprotocol
DCOM sits right in the middle of the components fo your
application; it provides the invisible glue that ties things
together.
Location Independence
129
Conflicting design constraints…
… with DCOM are easy to work around, because the details of
deployment are not specified in the source code : DCOM
completely hides the location of a component
in practice, however, applications need to consider the two
primary constraints of a network connection:
• bandwidth
• latency
 preferred transport protocol : UDP
Connection Management
130
DCOM :
• manages connections to components that are dedicated to a
single client, as well as components that are shared by
multiple clients, by mantaining a reference count on each
component
• uses an efficient pinging protocol to detect if clients are still
active
• takes advantage of Windows NT support for
multiprocessing for enhancing applications’ scalability
Security by Configuration
131
4) Fail or allow call
3) Is user in
the list?
2) Authenticate user
1) DCOM obtains
user name
Security on the Internet
132
DCOM uses the security framework provided by
Windows NT , this supports multiple security
providers including :
• Windows NT NTLM authentication protocol
• the Kerberos Version 5 authentication protocol
• distributed password authentication
• secure channel security services
• a DCE-compliant security provider
Weaknesses of COM/DCOM
133
 COM/DCOM is hard to use
 COM is not robust enough for enterprise
deployments
 Microsoft is walking to turn COM and the MTS into one
programming model that will simplify the lives of developers
building distributed, enterprise-wide COM applications
• COM/DCOM are best supported on Windows 95 and NT
platforms
• low cost development tools provide the ability to build and
access COM components for Windows platforms, for other
platforms the prices are considerably more expensive
Comparison of
DCOM, CORBA, RMI
134
Java RMI comes from JavaSoft
CORBA is a specification resulting from OMG
DCOM comes from Microsoft
Their main goal :
to provide an infrastructure to enable writing distributed
applications with relative ease, although they do so in
different ways
Java RMI
135
 Very easy to use
 Remoteable interfaces have a special exception
 Supports object-by-value
 Versioning is built into serialization
•
Callbacks are blocked in synchronized methods
•
Not always intuitive
•
Not available to other languages
• There are limited development tools
•
Performance can be slow as you scale
CORBA
136
1/2
 Architecture for system composition
 Has a standard terminology for concepts
 Declarative interfaces separate the interface
from the implementation
 Provides mappings from IDL to C, C++, SmallTalk
and Java
 Supports :
evolvable and marshallable data
 design portability
 standard interoperability protocols

 Scalable for large systems
CORBA
2/2
137
 No inheritance for Exceptions
 Objects cannot support two versions of the same






interface
IDL is not internationalized
Divergent security mechanisms (Kerberos, SSL)
Few advanced services
C++ mapping has complicated memory management
rules
Limited developer tools (usually just an IDL
compiler)
Limited concurrency model
DCOM
 Lots of tools, books and138
developers
 Separates interface from implementation
 Good integration of automation objects with
VisualBasic and Java
 Good set of compound document interfaces
 Microsoft depends on it working
• Minimal support on non-Microsoft platforms
• Hard to keep registry consistent
• Reference counting is a problem
• Client has to choose the interaction model
So, What Shall I Use?
1/2
139
 Requirement : no recompilation moving applications
to various platforms
 the Java/CORBA solution may be more appropriate then
COM
• Requirement : interaction with DCOM objects
 pure DCOM solution
So, What Shall
I Use?
140
2/2
• Requirement : distributed application written entirely in Java
 RMI for its ease of programming
• Requirement: plug-in components created by third parties
 components may be based around a DCOM or CORBA
interface
T H E END
END
THE
141
ActiveX
1/2
142
 Technology developed by Microsoft for sharing
information among different applications
 Outgrowth of OLE and COM
 supports new features that enable it to take
advantage of the Internet
 Not a programming language but a set of rules for how
applications should share information
ActiveX
2/2
143
 ActiveX control
 similar to Java applet but :
 full
access to the Windows operating system
 limitated to Windows environments

can be developed in a variety of languages

THETOPPERSWAY.COM
back
Download