A Little More Java Servlets - PowerPoint PPT Presentation

1 / 60
About This Presentation
Title:

A Little More Java Servlets

Description:

Servlets are modules that run inside request/response-oriented ... We haven't explained this, so treat this as an idiom. Open a Connection to the Database ... – PowerPoint PPT presentation

Number of Views:246
Avg rating:3.0/5.0
Slides: 61
Provided by: walterma
Category:
Tags: idiom | java | more | servlets

less

Transcript and Presenter's Notes

Title: A Little More Java Servlets


1
A Little More JavaServlets
  • Based on lectures by Walter Makovoz, Ph.D.

2
NETWORK INTERFACES
  • Java provides a full range of network interfaces
    for client / server communications
  • Two types of sockets are supported
  • connection-oriented (TCP)
  • connection-less (UDP)

3
Servlets
  • Servlets are modules that run inside
    request/response-oriented servers, such as
    Java-enabled web servers, and extend them in some
    manner. For example, a servlet might be
    responsible for taking data in an HTML
    order-entry form and applying the business logic
    used to update a company's order database.
    Servlets are to servers what applets are to
    browsers.
  • The Servlet API, which you use to write servlets,
    assumes nothing about how a servlet is loaded,
    the server environment in which the servlet runs,
    or the protocol used to transmit data to and from
    the user. This allows servlets to be embedded in
    many different web servers.
  • Servlets are an effective substitute for CGI
    scripts they provide a way to generate dynamic
    documents that is both easier to write and faster
    to run. They also address the problem of doing
    server-side programming with platform-specific
    APIs. Servlets are developed with the Java
    Servlet API, a standard Java extension. While it
    is not part of the core Java framework, which
    must always be part of all products bearing the
    Java brand, it will be made available with such
    products by their vendors as an add-on package.
    It is already supported by many popular web
    servers.

4
Servlets
  • In some ways, a servlet is similar to an applet.
    An applet is a chunk of Java code that executes
    under control of a browser. A servlet is a chunk
    of Java code that executes under control of a
    server program.

5
Servlets
  • According to JavaSoft
  • The servletrunner is a small utility, intended
    for testing. It is multithreaded, so it can run
    more than one servlet. It can be used therefore,
    to run multiple servlets simultaneously, or to
    test one servlet that calls other servlets in
    order to satisfy client requests. Unlike some web
    servers, it does not automatically reload
    servlets when they are updated. Because it is
    small, however, there is very little overhead
    associated with stopping and restarting it in
    order to use a new version of a servlet.

6
Servlets
  • The purpose of this program is to illustrate a
    very simple servlet.
  • The servlet was tested using the JDK 1.2 download
    package
  • from JavaSoft along with the Java Servlet
    Development Kit
  • (JSDK) 2.0 from JavaSoft. All tests were
    performed under Win95.
  • The servlet was tested using the servletrunner
    program that
  • is included in the JSDK with the servletrunner
    program
  • running on the same machine and also with the
    servletrunner
  • program running on a different machine on the
    network.
  • The servlet was also tested using the JavaSoft
    Java Web
  • Server 1.1.1 program running on a different
    machine on the network.
  • The servlet produces the following text in the
    browser
  • window in large red letters.
  • Hello Big Red World

7
Servlets
  • import java.io.
  • import javax.servlet.import javax.servlet.http.
  • public class Servlet01 extends HttpServlet
  • public void doGet(HttpServletRequest req,
  • HttpServletResponse res)
  • throws ServletException,
    IOException
  • //Establish the type of output
    res.setContentType("text/html")
  • //Get an output stream PrintWriter out
    res.getWriter()
  • //Construct an HTML page to return to the
    client out.println("ltHTMLgt")
  • out.println("ltHEADgtltTITLEServlet01lt/TITLEgtlt/H
    EADgt")
  • out.println("ltBODYgt")
    out.println("lth1 align\"center\"gt"
  • "ltfont color\"FF0000\"gt")
  • out.println("Hello Big Red World")
    out.println("lt/fontgtlt/h1gt")
  • out.println("lt/BODYgtlt/HTMLgt") //end
    doGet()//end class Servlet01

8
Servlets
  • All servlets must implement the Servlet
    interface. You can implement it directly.
    However, it is more common to implement it
    indirectly by extending a class that implements
    the interface (such as HttpServlet).
  • The Servlet interface declares methods for
    managing the servlet and its communications with
    clients. You will need to provide some or all of
    these methods when you write your servlet.

9
Servlets
  • Two objects are passed to a servlet when it
    called by a client
  • ServletRequest - encapsulates the communication
    from the client to the server.
  • ServletResponse - encapsulates the communication
    from the servlet back to the client

10
(No Transcript)
11
  • Figure 1. Servlet invocation.
  • An attractive alternative to CGI and proprietary
    server APIs
  • Supported accross different HTTP servers - Apache
    and most commercial servers support Servlet API
  • Third party Servlet API implementations
  • Java VMs
  • Integration with the host servers via their
    native APIs
  • Don't have to be HTTP-specific - may be used to
    implement complex multi-tier applications
  • See the javax.servlet package

12
  • Familiar model of accepting requests and
    submitting responses
  • Extend HTTPServet or GenericServlet classes
  • Access to servlet-specific configuration data at
    initialization time
  • Interact with their environment through a
    ServletContext object
  • Usage modes
  • Basic request/response mode
  • Servlet chaining for filtering
  • Specialized for HTTP - CGI replacement With SSI

13
  • Basic example
  • import javax.servlet.
  • public class MyServlet
  • extends GenericServlet
  • public void service (
  • ServletRequest request,
  • ServletResponse response
  • ) throws ServletException, IOException
  • ServletInputStream
  • in request.getInputStream ()
  • ServletOutputStream
  • out response.getOutputStream ()
  • ...

14
  • The API consists of 2 packages, 12 interfaces,
    and 9 classes
  • javax.servlet
  • Interface RequestDispatcher - defines an object
    that receives client requests and forwards them
    to a proper resource.
  • Interface Servlet - defines and object that
    extends functionalioty of a Web server.

15
  • Interface ServletConfig - defines an object that
    controls servlet configuration (unique for every
    servlet).
  • Interface ServletContext - defines an object that
    provides a servlet with information about the
    environment.
  • Interface ServletRequest - defines an object that
    enables the servlet to get data about a client
    request.
  • Interface ServletResponse - defines an object
    that enables the servlet to respond to the client
    request.
  • Interface SingleThreadModel - empty interface,
    the purpose is to flag servlets for sequential
    execution.

16
  • Class GenericServlet - holds a reference to the
    ServletConfig and ServletContext objects (created
    at initialization time), provides simple
    implementations of the servlet lifecycle methods.
  • Class ServletInputStream - input stream for
    reading clienbt requests.
  • Class ServletOutputStream - abstract class,
    implemented by all servlet engines, utilized to
    retrun data to clients.
  • Class ServletException - thrown to indicate a
    servlet problem.
  • Class UnavailableException - thrown to indicate
    servlet's unavailability.
  • java.servlet.http

17
  • Interface HttpServletRequest extends
    ServletRequest - defines an object that enables
    the servlet to access http-specific request
    information from the client request (e.g.,
    getAuthType(), getCookies(), getHeader(String
    name), getSession(), etc.)
  • Interface HttpServletResponse extends
    ServletResponse - defines an object that
    represents an http response back to the client.
  • Interface HttpSession - provides an association
    between an HTTP client and an HTTP session
    (implemented through cookies or URL rewriting).

18
  • Interface HttpSessionBindingListener - objects
    implement this interface if they wish to be
    notified about being bound to or unbound from a
    session.
  • Interface HttpSessionContext - deprecated
    (originally introduced to define common context
    for multiple sessions).
  • Class Cookie - represents a Cookie as defined in
    RFC 2109.

19
  • Class HttpServlet extends GenericSevlet -
    provides convenience in iumplementing HTTP
    servlets (e.g., doGet(HttpServletRequest request,
    HttpServletResponse response), doPost(HttpServletR
    equest request, HttpServletResponse response),
    doPut(HttpServletRequest request,
    HttpServletResponse response), etc.).
  • Class HttpSessionBindingEvent - this event is
    communicated to a HttpSessionBindingListener.
  • Class HttpUtils - a collection of static utility
    methods useful to HTTP servlets (e.g.,
    parseQueryString(String s), etc.).

20
(No Transcript)
21
  • Figure 2. Servlet Lifecycle.
  • Dynamic loading (using normal Java class loading
    facilities) and loading on server startup
  • Servlet initialization - provide your own
    implementation of the init() method to perform
    i/o-intensive setup once vs. per request (e.g.,
    initializing access to other network services or
    retrieving the state)
  • One service() call per request, class-static data
    may be used to share info between requests
  • Servlet remains active until shut down using the
    destroy() method, after which the class may
    become eligible for garbage collection

22
(No Transcript)
23
  • Figure 3. Servlet security.
  • Access to client information, HTTP-specific
    servlets - access to HTTP authentication data
  • Faulty servlets don't crash servers - not true
    for proprietary APIs
  • Java VM becomes part of the server - Java
    Security Manager - control over network and file
    access
  • Unique feature of Java
  • Fundamental difference from proprietary C and C
    server APIs and scripting interfaces
  • Untrusted and trusted (e.g., built-in and those
    that live in a designated local directory, signed
    servlets in JAR files) - different access
    priviliges
  • Possible for ISPs to accept servlets from their
    customers (native API server extensions are
    disallowed because of security)

24
  • Servlet Roles
  • HTTP request processing - CGI-style
  • Same functionality may be achieved with CGIs
  • Support for GET, POST, HEAD, etc.
  • Superior performance and security
  • Servlets responsible for HTML generation
  • Server-side includes via the SERVLET tag
  • Syntax
  • ltSERVLET NAMEServletNamegt
  • ltPARAM NAMEparam1 VALUEval1gt
  • ltPARAM NAMEparam2 VALUEval2gt
  • Alternative text
  • lt/SERVLETgt
  • Example to support a database search

25
  • Discussed so far
  • Introduction to Java
  • Learned how to use the tools in the JDK
  • Application programming in Java using OO concepts
  • Simple Java GUIs using AWT
  • Writing Applets in Java
  • Multi-threading
  • Networking
  • URL Networking
  • Socket Networking
  • Missing one critical component
  • Database access!

26
  • Database Access in Java
  • SQL and Relational DBs
  • Using SQL in Java JDBC
  • Problems with Relational DBs
  • Some approaches to resolving those problems
  • Outline
  • Motivation
  • Introduction to JDBC
  • JDBC Drivers
  • Using JDBC in applets
  • Middleware
  • Steps in accessing DBs via JDBC
  • Sample JDBC application

27
  • What is the foundation of Computing?
  • Data, Information
  • Computers are noting more than number crunchers
    at the grass-roots level!
  • What proof do we have that Data is a critical
    component of the IT infrastructure?
  • Oracle is the 2 software company in the world
  • their primary product is Database
  • It is impossible to write a serious application
    without requiring some form of persistence.
  • How useful would Microsoft Word be if you
    couldnt Save!?
  • Data is essential
  • CRUD cycle Create, Read, Update, Write

28
  • Were going to ASSUME you all know what a
    database is!
  • This is not a Database class!
  • Just a refresher
  • Types of databases
  • Hierarchical or Flat-file
  • Relational
  • Object
  • Some products
  • Oracle 8
  • SQL Server 7
  • Sybase, Informix
  • and believe it or not Microsoft Access

29
  • Commonalities between DBs
  • Most databases today
  • are built as Relational Databases
  • support SQL
  • SQL
  • Structured Query Language
  • A REALLY simple language with a total of about
    15-20 keywords which make it possible to perform
    CRUD operations on databases.
  • Assumption
  • You should all be familiar with SQL!
  • If not, then please pick up a book

30
  • Database Access in Java
  • Since MOST Databases support SQL
  • simplest way to have Java access a database is to
    be able to use SQL!
  • JDBC
  • Java DataBase Connectivity API
  • Provides an SQL interface to Databases
  • JDBC allows us to
  • load an appropriate JDBC driver for the
    database we are using
  • open a connection to the database using URL
    notation
  • embed SQL calls within Java code!
  • Create a new SQL Query or Update statement
  • Execute the query or update on the Database
  • Process results

31
  • JDBC/ODBC
  • ODBC
  • Microsofts Open Database Connectivity Standard
  • Proprietary standard from Microsoft!
  • Already exists in every Windows 95 and Windows NT
    machine!
  • JDBC
  • similar in design to ODBC
  • made a little bit more generic than ODBC
  • a LOT easier to use!
  • supports the ANSI SQL92 Entry Level
  • Accessing a JDBC/ODBC data source
  • Each database vendor MUST provide a driver
    (API) which conforms to the JDBC or ODBC
    specification!

32
  • JDBC Drivers
  • Type 1 JDBC-ODBC bridge
  • provides access to a the database by translating
    JDBC calls into ODBC calls understood by the
    Database
  • Type 2 native-API partly-Java driver
  • converts JDBC calls into native calls supported
    by the underlying database
  • Type 3 net-protocol all-Java driver
  • translates JDBC calls into a DBMS-independent net
    protocol which is then translated to a DBMS
    protocol by a server
  • Type 4 native-protocol all-Java driver
  • converts JDBC calls into the network protocol
    used by DBMSs directly

33
  • Using JDBC in Applets
  • Remember
  • Applets can ONLY communicate back to their
    CODEBASE!
  • Applets can only load pure Java classes from
    their CODEBASE
  • Implications
  • Only Type 3 and Type 4 drivers may be used in
    Java Applets
  • Type 1 and Type 2 contain native code which may
    not be executed within a Java applet!
  • Workarounds
  • Three-Tier architectures for allowing database
    access via applets
  • Signed/Trusted Applets which can break out of the
    Applet Sandbox

34
  • Middleware products
  • Provide a server on the CODEBASE machine which
    listens for Database requests and forwards the
    requests to the correct Database!
  • Example
  • dbAnywhere from Symantec included in their Visual
    Caf? for Java product
  • Lots of other Middle ware products out there!

35
  • Getting ready to use JDBC
  • For our Demo
  • We will use JDBC in an application since an
    application has no security restrictions
  • We will use the JDBC-ODBC bridge (Type 1 driver)
    since the only database we can have here is
    Microsoft Access
  • Other pre-requisites
  • Database must be installed
  • ODBC driver must be installed in Control Panels
  • JDBC is only included in JDK1.1!
  • JDBC-ODBC bridge driver must be installed
  • included in JDK1.1

36
  • Setting up the Database
  • Create a new Database
  • AddressBookDB
  • ID, firstName, lastName, middleInitial,
    addressLine1, addressLine2, city, state, zip,
    country, phone, fax, email
  • Create a DSN for the Database
  • DSN Data Source Name
  • tells your program which database to use!
  • Done in the ODBC control panel
  • Well use the AddressBookDSN
  • Remember the DSN since that is what will be
    required in the URL to the Database for ODBC!!

37
  • The Database URL
  • Syntax
  • jdbcltsub-protocolgtltsubnamegt
  • Example
  • jdbcodbcAddressBookDSN
  • Network addressing
  • jdbcdbnet//wombat.eng.sun.com356/fred
  • For details please see the JDBC Specification at
  • http//java.sun.com80/products/jdbc/index.html

38
  • Steps in using JDBC
  • Load the appropriate JDBC driver
  • Done using dynamic class loading in Java
  • We havent explained this, so treat this as an
    idiom
  • Open a Connection to the Database
  • Create a new query as an SQL Statement
  • Execute the query
  • Process the ResultSet
  • for database meta-data and the records
  • Close the Statement
  • Close the ResultSet
  • Close the database connection

39
  • Sample Application
  • Simple SELECT call into a DB
  • First a quick look at the JDBC API
  • java.sql.
  • Lets go to the code for
  • SelectDB.java

40
  • Analysis of Example
  • We only did a simple Select call
  • This application will work with ANY database!
  • To update the database or add to the DB
  • use an INSERT SQL statement
  • Statement.executeUpdate()
  • You now have the building blocks for doing more
    esoteric JDBC applications!!

41
  • Problems with Relational DBs
  • Remember Assignment Two
  • Person, Student, Instructor, Lecturer, Course,
    Grade etc?
  • What would it take to take all of that data and
    STORE and RETRIEVE it from a database!!
  • Many classes contained One to Many or even Many
    to Many mappings!
  • Each student had many Grade objects keyed by
    Course
  • Need to convert from Object world into
    Relational world
  • Object-Relational Mapping
  • by far the most time consuming and error prone
    part of doing persistence in Java using JDBC
  • Need to provide method which can convert
  • Relational -gt Object data
  • Object -gt Relational data

42
  • More Esoteric Databases
  • Object Databases
  • Store each object in the database
  • Do not have the concept of storing tables
  • OQL
  • Object Query Language
  • analog of SQL for relational databases
  • Some products
  • POET
  • ObjectStore
  • Versant
  • For more information
  • Object Database Management Group (www.odmg.org)

43
  • Other solutions
  • JavaBlend
  • automates the process of mapping from Object to
    Relational world and vice versa
  • Still in Beta
  • early access release is out
  • Several other vendors provide their own tools to
    create relational to object mappings
  • how useful they are depends on how convoluted
    your data model is!

44
  • Status
  • Seen a brief introduction to JDBC
  • You have all the building blocks to build more
    esoteric JDBC applications!

45
(No Transcript)
46
  • Servlet performance.
  • Performance advantages over both CGI and FastCGI
  • CGI - heavy startup and initialization code on
    each request
  • FastCGI - heavy process context switching per
    request
  • Servlets
  • Light-weight process context switching per
    request, initalization costs spread over multiple
    requests
  • Automatically takes advantage of JVM permance
    features (running threads on different
    processors, etc.)

47
(No Transcript)
48
(No Transcript)
49
(No Transcript)
50
(No Transcript)
51
Interfaces
  • Similar to a class but the methods are only
    declared (not defined) and the data attributes
    must be initialized and are treated as "static
    final" (constants)
  • All attributes in an interface must be public
  • Any class that implements an interface is
    responsible for defining all of the methods
    declared in that interface

52
  • class Client
  • Socket socket
  • public PrintStream out
  • public Client(String host, int port)
  • try
  • socket new Socket(host, port)
  • out new PrintStream(socket.getOutputStream())
  • catch (IOException e)
  • public void close()
  • try
  • socket.close()

53
Server (Receive.java)
  • import java.io.
  • import java.net.
  • public class Receive
  • public static void main(String args)
  • Server server new Server(1234)
  • try
  • String data
  • while ((data server.in.readLine()) ! null)
  • System.out.println(data)
  • catch (IOException e)

54
  • class Server
  • ServerSocket listen
  • Socket socket
  • public DataInputStream in
  • public Server(int port)
  • try
  • listen new ServerSocket(port, 30)
  • socket listen.accept()
  • in new DataInputStream(socket.getInputStream())
  • catch (IOException e)

55
  • Classes can inherit multiple interfaces (but can
    inherit only one super class)
  • Interfaces can inherit multiple interfaces
  • Unlike classes, interface inheritance is not
    based on a single inheritance tree

56
  • Defining an interface
  • package Employee
  • interface EmpInterface
  • float weeklyPay()
  • String toString()
  • Implementing an interface
  • package Employee
  • public class Emp implements EmpInterface
  • // must define public versions of weeklyPay() and
    toString()

57
ABSTRACT CLASSES
  • An "abstract class" is an intermediate step
    between an interface and a class
  • An abstract class can contain both implemented
    and unimplemented (abstract) methods
  • No objects can be created from an abstract class

58
Interfaces
  • Regular classes that inherit from an abstract
    class must provide definitions for all inherited
    abstract methods
  • Abstract classes that inherit from an abstract
    class may either provide definitions for
    inherited abstract methods or leave them
    "abstract"

59
  • Defining an abstract class
  • abstract class EmpAbs
  • protected int idNum
  • protected String name
  • protected float hoursWorked
  • protected float hourlyRate
  • abstract public float weeklyPay() // an abstract
    method
  • public EmpAbs(int id, String n, float h, float r)
  • idNum id
  • name new String(n)
  • hoursWorked h
  • hourlyRate r
  • public String toString()
  • return(idNum "\t" name "\t"
  • hoursWorked "\t" hourlyRate)

60
I/O STREAMS
  • Input and output are handled by a package of
    classes
  • InputStream
  • int c System.in.read()
  • InputStream filein new FileInputStream("filename
    ")
  • c filein.read()
  • OutputStream
  • System.out.write(c)
  • System.err.println("Error!")
  • OutputStream fileout new FileOutputStream("filen
    ame")
  • fileout.write(c)
Write a Comment
User Comments (0)
About PowerShow.com