Transcript JSPandJDBC

Java Server Pages
Java Server Pages
• Servlets are nice, but…
– It’s 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 don’t need to know Java
– Programmers don’t need to know design
My First JSP
<html>
<head>
<title>Greetings</title>
</head>
<body>
<%
for(int i=0;i<8;i++)
{ %>
<p><font size=<%=i%>>Hello World!</font>
<%
} %>
</body>
</html>
http://localhost:8080/ServletsAndJSP/HelloWorld.jsp
Java Server Pages
• Allow you to insert code into the HTML
– Expressions <%= expression %>
– Scriptlets <% code %>
– Declarations <%! code %>
• Upon access, the JSP is converted to a
servlet then executed
– Same life cycle as a servlet
JSP Expressions
• <%= Java Expression %>
– Evaluated, Converted to a string, Inserted
• Current Time: <%= new java.util.Date() %>
• Predefined Variables
–
–
–
–
–
–
–
request
response
session
out
application
config
pageContext
the HttpServletRequest
the HttpServletResponse
the HttpSession
the PrintWriter
the ServletContext
the ServletConfig
the PageContext
JSP Code
• <% code %>
– Just executed
• <% for(int j = 0; j < 8; j++)
{ %>
<p><font size=<%= j %>>Hi</font>
<% } %>
• <%-- JSP Comment --%>
• <!– HTML Comment -->
JSP Declarations
• <%! Code %>
• Variable declarations
• <%! private int accessCount = 0; %>
Accesses: <%= ++accessCount %>
• Variables have class scope
– Shared between all instances
JSP directives
• Affect the overall structure of the page
• <%@ directive attribute=“value” %>
• The page directive
– <%@ page import=“java.util.*” %>
– <%@ page contentType=“text/plain” %>
– <%@ page session=“true” %> <%-- default --%>
• The include directive
– <%@ include file=“Navbar.jsp” %>
• Translation time
– <jsp:include page=“Navbar.jsp” flush=“true”/>
• Request time
Java Beans
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
Bean Usage
• <jsp:useBean id=“beanvar” class=“pkg.class” />
• Similar to:
– <% beanvar = new pkg.class(); %>
• More powerful
– Scope
(page, application, session, request)
• Bean Location
– Must be in server’s regular class path
Bean Usage
• Getting values
– <jsp:getProperty name=“className”
property=“variableName” />
• Setting values
– <jsp:setProperty name=“className”
property=“variableName”
value=“The String Value” />
– Or
param=“NumberVariable” />
My First Bean
public class MessageBean
{
private String message = "No String Specified";
public String getMessage()
{
return (message);
}
public void setMessage(String theMessage)
{
message = theMessage;
}
}
The JSP
…
<jsp:useBean id="myBean" class="MessageBean" scope="session" />
<ol>
<li>Initial Value: <i><jsp:getProperty name="myBean" property="message" /></i>
<jsp:setProperty name="myBean" property="message" value="Howdy" />
<li>After jsp:setProperty :
<i><jsp:getProperty name="myBean" property="message" /></i>
<% myBean.setMessage("After Scriptlet"); %>
<li>After scriptlet : <i><%= myBean.getMessage() %></i>
</ol>
http://localhost:8080/ServletsAndJSP/MessageBean.jsp
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
JSP Custom Tags
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)
My First Custom JSP Tag Handler
package mytaglib;
import javax.servlet.jsp.*;
import 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);
}
}
The Entry in web.xml
Note: web.xml is in WEB-INF directory
<web-app>
<servlet>
…
</servlet>
…
<taglib>
<taglib-uri>SimpleTag</taglib-uri>
<taglib-location>SimpleTag.tld</taglib-location>
</taglib>
…
</web-app>
The Tag Library Descriptor
Note: This is SimpleTag.tld. It goes in the WEB-INF directory
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>simpletag</shortname>
<urn></urn>
<info>
My tag example.
</info>
<tag>
<name>example</name>
<tagclass>mytaglib.SimpleTag</tagclass>
<info>Simple example</info>
<bodycontent>EMPTY</bodycontent>
</tag>
</taglib>
The JSP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transistional//EN">
<html><head>
<%@ taglib uri=“SimpleTag" prefix="simpletag" %>
<title><simpletag:example /></title>
</head>
<body>
<h1><simpletag:example /></h1>
Here is the output from the tag: <i><simpletag:example /></i>
</body>
</html>
http://localhost:8080/ServletsAndJSP/SimpleTagExample.jsp
Tag Handler
• Must implement the
javax.servlet.jsp.tagext.Tag interface
• doStartTag() and doEndTag() are key
methods
• Frequently extend TagSupport
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.
* <P>
*/
public class DebugTag extends TagSupport
{
public int doStartTag()
{
ServletRequest request = pageContext.getRequest();
String debugFlag = request.getParameter("debug");
if ((debugFlag != null) && (!debugFlag.equalsIgnoreCase("false")))
{
return(EVAL_BODY_INCLUDE);
}
else
{
return(SKIP_BODY);
}
}
}
TLD File
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
TLD File (Cont)
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>csajsp</shortname>
<info></info>
<tag>
<name>debug</name>
<tagclass>mytaglib.DebugTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Includes body only if debug param is set.</info>
</tag>
</taglib>
web.xml entry
<taglib>
<taglib-uri>Debug</taglib-uri>
<taglib-location>DebugTag.tld</taglib-location>
</taglib>
JSP Usage
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
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.
-->
<HTML>
<HEAD>
<TITLE>Using the Debug Tag</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1>Using the Debug Tag</H1>
<%@ taglib uri="Debug" prefix="csajsp" %>
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
<P>
<csajsp:debug>
<B>Debug:</B>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Requesting hostname: <%= request.getRemoteHost() %>
<LI>Session ID: <%= session.getId() %>
</UL>
</csajsp:debug>
<P>
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
</BODY>
</HTML>
Execute:
http://localhost:8080/ServletsAndJSP/DebugTagExample.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.
Execute:
http://localhost:8080/ServletsAndJSP/DebugTagExample.jsp?debug=true
Using the Debug Tag
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
Debug:
•Current time: Fri Jan 25 08:29:51 MST 2002
•Requesting hostname: 128.187.172.118
•Session ID: 320162B94289B579C523641021B008A1
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
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
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
JDBC
Simple JDBC Program
•
•
•
•
•
Load JDBC Driver implementation
Obtain connection to driver/database
Execute query
Process query results
Release resources
Example Program
Step 1 - Load the Driver
import java.sql.*;
try
{
Class.forName(“org.gjt.mm.mysql.Driver”);
}
catch(ClassNotFoundException)
{
// Couldn’t find JDBC driver to load !
}
Example Program
Step 2 - Obtain a Connection
Connection con =
DriverManager.getConnection(
“jdbc:mysql:///test”, “user”,
“password”
);
JDBC URLs
• URL specifies the driver (subprotocol) and the data source/database
system
– Example. jdbc:mysql:///test
– jdbc:driver:databasename
• 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
– jdbc:odbc:datasource;dataoptions
– jdbc:oracle:thin:@aplcen.apl.jhu.edu:1521:petStore
– jdbc:cloudscape:petStoreDB
• 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.
Example Program
Step 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.
Example Program
Step 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
Example Program
Step 5 - Release Resources
rs.close();
st.close();
con.close();
Statement
• Represents a basic SQL statement
• Created from a connection
• Use executeQuery for queries
– Result rs=st.executeQuery(“SELECT * FROM Image”);
• Use executeUpdate for SQL statements that don’t
return results
– DDL commands for creating, dropping tables
– Update/Delete
– Returns the number of rows affected
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 i=0; i<10; i++) {
ps.setInt(1, i);
ResultSet rs = ps.executeQuery();
// Do something with the result set
}
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)
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
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
DatabaseMetaData
• DatabaseMetaData md =
con.getMetaData();
• Operations include:
–
–
–
–
get database product name
get driver version
get all tables
get all indexes
ResultSetMetaData
• ResultSetMetaData md = rs.getMetaData();
• Operations to get:
– Number of columns (getColumnCount())
– Column Name (getColumnLabel())
– Column Type (getColumnTypeName())
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
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();
SQL Types and Java
•
•
•
•
•
INTEGER -> int
NUMERIC -> java.sql.Numeric
FLOAT(n) -> double
REAL -> float
DOUBLE -> double
CHAR(n) -> String
BOOLEAN -> boolean
ARRAY -> 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
Batch Updates
con.setAutoCommit(false);
Statement s = con.createStatement();
s.addBatch(….);
s.addBatch(…..);
……
s.executeBatch();
con.commit();
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
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/jdbc)
• Object/Relational Database Mapping by
Claude Duguay. Java Pro, January 2000