Java Server Pages - PowerPoint PPT Presentation

1 / 54
About This Presentation
Title:

Java Server Pages

Description:

Java Server Pages – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 55
Provided by: quinno
Category:

less

Transcript and Presenter's Notes

Title: Java Server Pages


1
Java Server Pages
2
Java Server Pages
  • Servlets are nice, but
  • Its a pain to put in all those out.println stmts
  • JSPs mix Java and HTML
  • Within the same document
  • Nice for team based projects
  • Web page designers dont need to know Java
  • Programmers dont need to know design

3
My First JSP
lthtmlgt ltheadgt lttitlegtGreetingslt/titlegt lt/headgt ltbo
dygt lt for(int i0ilt8i) gt ltpgtltfont
sizeltigtgtHello World!lt/fontgt lt
gt lt/bodygt lt/htmlgt http//localhost8080/Servlets
AndJSP/HelloWorld.jsp
4
Java Server Pages
  • Allow you to insert code into the HTML
  • Expressions lt expression gt
  • Scriptlets lt code gt
  • Declarations lt! code gt
  • Upon access, the JSP is converted to a servlet
    then executed
  • Same life cycle as a servlet

5
JSP Expressions
  • lt Java Expression gt
  • Evaluated, Converted to a string, Inserted
  • Current Time lt new java.util.Date() gt
  • Predefined Variables
  • request the HttpServletRequest
  • response the HttpServletResponse
  • session the HttpSession
  • out the PrintWriter
  • application the ServletContext
  • config the ServletConfig
  • pageContext the PageContext

6
JSP Code
  • lt code gt
  • Just executed
  • lt for(int j 0 j lt 8 j)
    gt ltpgtltfont sizelt j gtgtHilt/fontgt lt
    gt
  • lt-- JSP Comment --gt
  • lt! HTML Comment --gt

7
JSP Declarations
  • lt! Code gt
  • Variable declarations
  • lt! private int accessCount 0 gt Accesses
    lt accessCount gt
  • Variables have class scope
  • Shared between all instances

8
JSP directives
  • Affect the overall structure of the page
  • lt_at_ directive attributevalue gt
  • The page directive
  • lt_at_ page importjava.util. gt
  • lt_at_ page contentTypetext/plain gt
  • lt_at_ page sessiontrue gt lt-- default --gt
  • The include directive
  • lt_at_ include fileNavbar.jsp gt
  • Translation time
  • ltjspinclude pageNavbar.jsp flushtrue/gt
  • Request time

9
Java Beans
10
Java Beans
  • What is a bean?
  • Data structure that conforms to certain rules
  • Bean rules
  • Must have a zero argument constructor
  • Generally named xxxBean
  • No public instance variables
  • Persistent values set/accessed through
  • setXxx
  • getXxx
  • Mostly used for persistent storage of data

11
Bean Usage
  • ltjspuseBean idbeanvar classpkg.class /gt
  • Similar to
  • lt beanvar new pkg.class() gt
  • More powerful
  • Scope (page, application, session, request)
  • Bean Location
  • Must be in servers regular class path

12
Bean Usage
  • Getting values
  • ltjspgetProperty nameclassName propertyva
    riableName /gt
  • Setting values
  • ltjspsetProperty nameclassName propertyva
    riableName valueThe String Value /gt
  • Or paramNumberVariable /gt

13
My First Bean
public class MessageBean private String
message "No String Specified" public String
getMessage() return (message) public
void setMessage(String theMessage) message
theMessage
14
The JSP
ltjspuseBean id"myBean" class"MessageBean"
scope"session" /gt ltolgt ltligtInitial Value
ltigtltjspgetProperty name"myBean"
property"message" /gtlt/igt ltjspsetProperty
name"myBean" property"message" value"Howdy"
/gt ltligtAfter jspsetProperty
ltigtltjspgetProperty name"myBean"
property"message" /gtlt/igt lt
myBean.setMessage("After Scriptlet") gt
ltligtAfter scriptlet ltigtlt myBean.getMessage()
gtlt/igt lt/olgt http//localhost8080/ServletsAndJSP
/MessageBean.jsp
15
Benefits and Limitations
  • Benefits
  • Separates business logic from HTML content
  • Easier maintenance
  • Component Re-usability
  • Can be configured with commercial tools
  • Limitations
  • No support for indexed properties

16
JSP Custom Tags
17
Custom JSP Tags
  • Tags encapsulate complex behaviors
  • Make them simple and accessible
  • Tags are essentially function calls to Java code
  • Consist of three pieces
  • The Tag Handler (Java code)
  • Defines the action
  • The Tag Library Descriptor (xml)
  • Identifies the tag to the server
  • The Entry in web.xml (xml)

18
My First Custom JSP Tag Handler
package mytaglib import javax.servlet.jsp. impo
rt javax.servlet.jsp.tagext. import
java.io. // Simple JSP tag that just inserts
the string "Simple Example Tag" public class
SimpleTagExample extends TagSupport public int
doStartTag() try JspWriter out
pageContext.getOut() out.print("Simple
Example Tag") catch(IOException
ioe) System.out.println("Error in
ExampleTag") return(SKIP_BODY)
19
The Entry in web.xmlNote web.xml is in WEB-INF
directory
ltweb-appgt ltservletgt lt/servletgt lttaglibgt
lttaglib-urigtSimpleTaglt/taglib-urigt
lttaglib-locationgtSimpleTag.tldlt/taglib-locationgt lt
/taglibgt lt/web-appgt
20
The Tag Library DescriptorNote This is
SimpleTag.tld. It goes in the WEB-INF directory
lt?xml version"1.0" encoding"ISO-8859-1"
?gt lt!DOCTYPE taglib PUBLIC "-//Sun
Microsystems, Inc.//DTD JSP Tag Library
1.1//EN" "http//java.sun.com/j2ee/dtds/web-jspta
glibrary_1_1.dtd"gt lttaglibgt lttlibversiongt1.0lt/t
libversiongt ltjspversiongt1.1lt/jspversiongt ltshortn
amegtsimpletaglt/shortnamegt lturngtlt/urngt ltinfogt M
y tag example. lt/infogt lttaggt ltnamegtexamplelt/n
amegt lttagclassgtmytaglib.SimpleTaglt/tagclassgt lt
infogtSimple examplelt/infogt ltbodycontentgtEMPTYlt/b
odycontentgt lt/taggt lt/taglibgt
21
The JSP
lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transistional//EN"gt lthtmlgtltheadgt lt_at_ taglib
uriSimpleTag" prefix"simpletag"
gt lttitlegtltsimpletagexample /gtlt/titlegt lt/headgt
ltbodygt lth1gtltsimpletagexample /gtlt/h1gt Here is
the output from the tag ltigtltsimpletagexample
/gtlt/igt lt/bodygt lt/htmlgt http//localhost8080/Ser
vletsAndJSP/SimpleTagExample.jsp
22
Tag Handler
  • Must implement the javax.servlet.jsp.tagext.Tag
    interface
  • doStartTag() and doEndTag() are key methods
  • Frequently extend TagSupport

23
Another Tag Handler Example
  • package mytaglib
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • import java.io.
  • import javax.servlet.
  • / A tag that includes the body content only if
  • the "debug" request parameter is set.
  • ltPgt
  • /

24
public class DebugTag extends TagSupport
public int doStartTag() ServletRequest
request pageContext.getRequest() String
debugFlag request.getParameter("debug")
if ((debugFlag ! null) (!debugFlag.equalsIgnor
eCase("false")))
return(EVAL_BODY_INCLUDE) else
return(SKIP_BODY)
25
TLD File
lt?xml version"1.0" encoding"ISO-8859-1"
?gt lt!DOCTYPE taglib PUBLIC "-//Sun
Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http//java.sun.com/j2ee/dtds/web-jsptaglibra
ry_1_1.dtd"gt
26
TLD File (Cont)
lttaglibgt lttlibversiongt1.0lt/tlibversiongt
ltjspversiongt1.1lt/jspversiongt ltshortnamegtcsajsplt/
shortnamegt ltinfogtlt/infogt lttaggt
ltnamegtdebuglt/namegt lttagclassgtmytaglib.DebugTag
lt/tagclassgt ltbodycontentgtJSPlt/bodycontentgt
ltinfogtIncludes body only if debug param is
set.lt/infogt lt/taggt lt/taglibgt
27
web.xml entry
lttaglibgt lttaglib-urigtDebuglt/taglib-urigt
lttaglib-locationgtDebugTag.tldlt/taglib-locat
iongt lt/taglibgt
28
JSP Usage
lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt lt!-- Taken from Core Servlets
and JavaServer Pages from Prentice Hall and Sun
Microsystems Press, http//www.coreservlets.com/.
copy 2000 Marty Hall may be freely used or
adapted. --gt ltHTMLgt ltHEADgt ltTITLEgtUsing the Debug
Taglt/TITLEgt ltLINK RELSTYLESHEET
HREF"JSP-Styles.css" TYPE"text/css"gt lt/HEA
Dgt ltBODYgt
29
ltH1gtUsing the Debug Taglt/H1gt lt_at_ taglib
uri"Debug" prefix"csajsp" gt Top of regular
page. Blah, blah, blah. Yadda, yadda,
yadda. ltPgt ltcsajspdebuggt ltBgtDebuglt/Bgt ltULgt
ltLIgtCurrent time lt new java.util.Date() gt
ltLIgtRequesting hostname lt request.getRemoteHost
() gt ltLIgtSession ID lt session.getId()
gt lt/ULgt lt/csajspdebuggt ltPgt Bottom of regular
page. Blah, blah, blah. Yadda, yadda,
yadda. lt/BODYgt lt/HTMLgt
30
Execute http//localhost8080/ServletsAndJSP/Deb
ugTagExample.jsp
Using the Debug Tag Top of regular page. Blah,
blah, blah. Yadda, yadda, yadda. Bottom of
regular page. Blah, blah, blah. Yadda, yadda,
yadda.
31
Execute http//localhost8080/ServletsAndJSP/Debu
gTagExample.jsp?debugtrue
  • Using the Debug Tag
  • Top of regular page. Blah, blah, blah. Yadda,
    yadda, yadda.
  • Debug
  • Current time Fri Jan 25 082951 MST 2002
  • Requesting hostname 128.187.172.118
  • Session ID 320162B94289B579C523641021B008A1
  • Bottom of regular page. Blah, blah, blah. Yadda,
    yadda, yadda.

32
Tag Complexity
  • Tags can become very complicated
  • Can parse body themselves
  • Can become nested in other tags
  • Ex. IF/THEN/ELSE
  • Looping constructs
  • While beans are generally used for model data and
    shared information, tags are typically confined
    to a single page

33
Tag Summary
  • Tags are a portable extension mechanism for jsp
  • Can build a library of components
  • Ex. XSLT renderer of XML data
  • Bridge to JavaBean model data
  • Ex. Setting indexed properties
  • Further eliminates the need for HTML authors to
    learn Java

34
JDBC
35
Simple JDBC Program
  • Load JDBC Driver implementation
  • Obtain connection to driver/database
  • Execute query
  • Process query results
  • Release resources

36
Example ProgramStep 1 - Load the Driver
  • import java.sql.
  • try
  • Class.forName(org.gjt.mm.mysql.Driver)
  • catch(ClassNotFoundException)
  • // Couldnt find JDBC driver to load !

37
Example ProgramStep 2 - Obtain a Connection
  • Connection con
  • DriverManager.getConnection(
  • jdbcmysql///test, user,
  • password
  • )

38
JDBC URLs
  • URL specifies the driver (subprotocol) and the
    data source/database system
  • Example. jdbcmysql///test
  • jdbcdriverdatabasename
  • Subprotocol specifies a particular kind of
    database connectivity that may be supported by
    more than one driver
  • Database name is free-form and only interpreted
    by the driver
  • Examples
  • jdbcodbcdatasourcedataoptions
  • jdbcoraclethin_at_aplcen.apl.jhu.edu1521petStore
  • jdbccloudscapepetStoreDB
  • The Driver Manager locates an appropriate driver
    (by calling each driver's getConnection(url)
    method) and returns a connection from the first
    driver that handles the subprotocol.

39
Example ProgramStep 3 - Execute a Query
  • try
  • Statement st con.createStatement()
  • ResultSet rs st.executeQuery(SELECT filename
    FROM Image)
  • catch(SQLException sqe)
  • // Problem
  • executeQuery() is used for Select statements
  • executeUpdate() is used for table creation and
    table modifications
  • executeBatch() to execute multiple statements.

40
Example ProgramStep 4 - Process Results
  • while(rs.next())
  • System.out.println(File
    rs.getString(filename))
  • The ResultSet cursor was positioned before the
    first row upon completion of the execute method

41
Example ProgramStep 5 - Release Resources
  • rs.close()
  • st.close()
  • con.close()

42
Statement
  • Represents a basic SQL statement
  • Created from a connection
  • Use executeQuery for queries
  • Result rsst.executeQuery(SELECT FROM Image)
  • Use executeUpdate for SQL statements that dont
    return results
  • DDL commands for creating, dropping tables
  • Update/Delete
  • Returns the number of rows affected

43
Prepared Statement
  • Pre-compiled SQL Statement
  • Better performance if a statement will be issued
    multiple times
  • PreparedStatement ps
  • con.prepareStatement(SELECT FROM Image WHERE
    image_id ?)
  • for( int i0 ilt10 i)
  • ps.setInt(1, i)
  • ResultSet rs ps.executeQuery()
  • // Do something with the result set

44
ResultSet
  • Encapsulates query results
  • while(rs.next())
  • String fname rs.getString(filename)
  • Column name is case-insensitive
  • JDBC 1.0 only allows forward-navigation
  • Column number may be used instead of name.
    (Column numbers start at 1)

45
ResultSet Navigation
  • New ResultSet Operations
  • first(), last(), next()
  • previous(), beforeFirst(), afterLast()
  • absolute(int), relative(int)
  • Rows may be updated and inserted
  • rs.update( 3, new filename) rs.updateRow()
  • Rows may be deleted

46
Dynamic Programs
  • Most programs know the database schema they are
    operating upon.
  • Some generic programs e.g. database table viewer
    need to discover the schema dynamically
  • DatabaseMetaData from Connection
  • ResultSetMetaData from ResultSet

47
DatabaseMetaData
  • DatabaseMetaData md
  • con.getMetaData()
  • Operations include
  • get database product name
  • get driver version
  • get all tables
  • get all indexes

48
ResultSetMetaData
  • ResultSetMetaData md rs.getMetaData()
  • Operations to get
  • Number of columns (getColumnCount())
  • Column Name (getColumnLabel())
  • Column Type (getColumnTypeName())

49
Transactions
  • Grouping of statements into one logical unit of
    work
  • Each statement must succeed or the transaction is
    rolled back
  • Steps
  • start transaction
  • execute statements
  • commit or rollback the transaction

50
JDBC Transaction API
  • Responsibility of the Connection Object
  • By default, each operation is a transaction
  • con.setAutoCommit(true)
  • To perform multiple statements in a transaction
  • con.setAutoCommit(false)
  • // execute statements
  • con.commit()

51
SQL Types and Java
  • INTEGER -gt int NUMERIC -gt java.sql.Numeric
  • FLOAT(n) -gt double REAL -gt float
  • DOUBLE -gt double CHAR(n) -gt String
  • BOOLEAN -gt boolean ARRAY -gt java.sql.Array
  • Date,Time, and Timestamp correspond to the sql
    types
  • java.sql.Date, java.sql.Time, java.sql.Timestamp
  • Large results can be treated as streams
  • getAsciiStream(), getBinaryStream()
  • Useful for images, etc.
  • getBlob and getClob added in JDBC 2.0
  • getObject() added for Java-aware databases

52
Batch Updates
  • con.setAutoCommit(false)
  • Statement s con.createStatement()
  • s.addBatch(.)
  • s.addBatch(..)
  • s.executeBatch()
  • con.commit()

53
JDBC Summary
  • Thin Java API for access to SQL databases
  • Allows portable access to databases from
    different vendors
  • Still need to know SQL
  • Different driver implementation strategies
  • With extensions, JDBC 2.0 has taken a large step
    forward

54
References
  • Developing Java Enterprise Applications
  • Sun Educational Services - Distributed
    Programming with Java (SL-301)
  • Java Enterprise in a Nutshell
  • Sun's JDBC website (http//java.sun.com/products/j
    dbc)
  • Object/Relational Database Mapping by Claude
    Duguay. Java Pro, January 2000
Write a Comment
User Comments (0)
About PowerShow.com