1 / 54

Java Server Pages

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.

btuohy
Download Presentation

Java Server Pages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Server Pages

  2. 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

  3. 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

  4. 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

  5. JSP Expressions • <%= Java Expression %> • Evaluated, Converted to a string, Inserted • Current Time: <%= new java.util.Date() %> • 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 • <% code %> • Just executed • <% for(int j = 0; j < 8; j++) { %> <p><font size=<%= j %>>Hi</font> <% } %> • <%-- JSP Comment --%> • <!– HTML Comment -->

  7. JSP Declarations • <%! Code %> • Variable declarations • <%! private int accessCount = 0; %> Accesses: <%= ++accessCount %> • Variables have class scope • Shared between all instances

  8. 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

  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 • <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

  12. 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” />

  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 … <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

  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.xmlNote: 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>

  20. The Tag Library DescriptorNote: 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>

  21. 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

  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. * <P> */

  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 <?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">

  26. 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>

  27. web.xml entry <taglib> <taglib-uri>Debug</taglib-uri> <taglib-location>DebugTag.tld</taglib-location> </taglib>

  28. 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>

  29. <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>

  30. 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.

  31. 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.

  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) { // Couldn’t find JDBC driver to load ! }

  37. Example ProgramStep 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 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 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();

More Related