Download presentation
Presentation is loading. Please wait.
Published byAshlyn Atkinson Modified over 9 years ago
1
Java Server Pages
2
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
3
My First JSP Greetings <% for(int i=0;i<8;i++) { %> >Hello World! <% } %> http://localhost:8080/ServletsAndJSP/HelloWorld.jsp
4
Java Server Pages Allow you to insert code into the HTML –Expressions –Scriptlets –Declarations Upon access, the JSP is converted to a servlet then executed –Same life cycle as a servlet
5
JSP Expressions –Evaluated, Converted to a string, Inserted Current Time: Predefined Variables –requestthe HttpServletRequest –responsethe HttpServletResponse –sessionthe HttpSession –outthe PrintWriter –applicationthe ServletContext –configthe ServletConfig –pageContextthe PageContext
6
JSP Code –Just executed >Hi
7
JSP Declarations Variable declarations Accesses: Variables have class scope –Shared between all instances
8
JSP directives Affect the overall structure of the page The page directive – The include directive – Translation time – Request time
9
Java Beans
10
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 Similar to: – More powerful –Scope(page, application, session, request) Bean Location –Must be in server’s regular class path
12
Bean Usage Getting values – Setting values – –Orparam=“NumberVariable” />
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 … Initial Value: After jsp:setProperty : After scriptlet : http://localhost:8080/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.*; 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); }
19
The Entry in web.xml Note: web.xml is in WEB-INF directory … … SimpleTag SimpleTag.tld …
20
The Tag Library Descriptor Note: This is SimpleTag.tld. It goes in the WEB-INF directory <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1 simpletag My tag example. example mytaglib.SimpleTag Simple example EMPTY
21
The JSP Here is the output from the tag: http://localhost:8080/ServletsAndJSP/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. * */
24
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); }
25
TLD File <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
26
TLD File (Cont) 1.0 1.1 csajsp debug mytaglib.DebugTag JSP Includes body only if debug param is set.
27
web.xml entry Debug DebugTag.tld
28
JSP Usage <!-- Taken from Core Servlets and JavaServer Pages from Prentice Hall and Sun Microsystems Press, http://www.coreservlets.com/. © 2000 Marty Hall; may be freely used or adapted. --> Using the Debug Tag <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">
29
Using the Debug Tag Top of regular page. Blah, blah, blah. Yadda, yadda, yadda. Debug: Current time: Requesting hostname: Session ID: Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
30
Execute: http://localhost:8080/ServletsAndJSP/DebugTagExample.jsp 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.
31
Execute: http://localhost:8080/ServletsAndJSP/DebugTagExample.jsp?debug=true 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.
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 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 ! }
37
Example Program Step 2 - Obtain a Connection Connection con = DriverManager.getConnection( “jdbc:mysql:///test”, “user”, “password” );
38
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.
39
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.
40
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
41
Example Program Step 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 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
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 i=0; i<10; 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 -> intNUMERIC -> java.sql.Numeric FLOAT(n) -> doubleREAL -> float DOUBLE -> doubleCHAR(n) -> String BOOLEAN -> booleanARRAY -> 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/jdbc)http://java.sun.com/products/jdbc Object/Relational Database Mapping by Claude Duguay. Java Pro, January 2000
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.