1 / 105

JSP – Java Server Pages

JSP – Java Server Pages. Representation and Management of Data on the Internet. Introduction. What is JSP Good For?. Servlets allow us to write dynamic Web pages Easy access to request, session and context data Easy manipulation of the response (cookies, etc.) And lots more...

ulla-berry
Télécharger la présentation

JSP – 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. JSP – Java Server Pages Representation and Management of Data on the Internet

  2. Introduction

  3. What is JSP Good For? • Servlets allow us to write dynamic Web pages • Easy access to request, session and context data • Easy manipulation of the response (cookies, etc.) • And lots more... • It is not convenient to write and maintain long static HTML using Servlets out.println("<h1>Bla Bla</h1>" + "bla bla bla bla" + "lots more here...")

  4. JSP Idea • Use HTML for most of the page • Write Servlet code directly in the HTML page, marked with special tags • The server automatically translates a JSP page to a Servlet class and the latter is actually invoked • In Tomcat 5.0 you can find the generated Servlet code under $CATALINA_BASE/work/

  5. Relationships • Servlets: HTML code is printed from Java code • JSP: Java code is embedded in HTML code Java HTML Java HTML

  6. Example <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H2><I><%=new java.util.Date()%></I></H2> <H1>Hello World</H1> </BODY> </HTML> Tomcat 5.0 Generated Servlet

  7. JSP Limitations and Advantages • JSP can only do what a Servlet can do • Easier to write and maintain HTML • Easier to separate HTML from code • Can use a "reverse engineering technique": create static HTML and then replace static data with Java code

  8. Basic JSP Elements

  9. Elements in a JSP file • HTML code: <html-tag>content</html-tag> • HTML comment: <!-- comment --> • JSP Comment: <%-- comment --%> • Expressions: <%= expression %> • Scriptlets: <% code %> • Declarations: <%! code %> • Directives: <%@ directive attribute="value" %> • Actions: discussed later

  10. JSP Expressions • A JSP expression is used to insert Java values directly into the output • It has the form: <%= expression %>, where expression can be a Java object, a numerical expression, a method call that returns a value, etc... • For example: <%= new java.util.Date() %> <%= "Hello"+" World" %> <%= (int)(100*Math.random()) %>

  11. JSP Expressions • A JSP Expression is evaluated • The result is converted to a string • The string is inserted into the page • This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request, the session, etc...

  12. public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { ... response.setContentType("text/html"); ... out.write("<H1>A Random Number</H1>\r\n"); out.print( Math.random() ); out.write("\r\n"); ... } Expression Translation <H1>A Random Number</H1> <%= Math.random() %>

  13. Predefined Variables (Implicit Objects) • The following predefined variables can be used: • request: the HttpServletRequest • response: the HttpServletResponse • session: the HttpSession associated with the request • out: the PrintWriter (a buffered version of type JspWriter) used to fill the response content • application: The ServletContext • These variables and more will be discussed in details

  14. <HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H2>JSP Expressions</H2> <UL> <LI>Current time: <%=new java.util.Date()%> <LI>Your hostname: <%= request.getRemoteHost() %> <LI>Your session ID: <%=session.getId() %> <LI>The <CODE>testParam</CODE> form parameter: <%=request.getParameter("testParam") %> </UL> </BODY> </HTML>

  15. JSP Scriplets • JSP scriptletslet you insert arbitrary code into the Servlet service method ( _jspService ) • Scriptlets have the form: <% Java Code%> • The code is inserted verbatim into the service method, according to the location of the scriplet • Scriptlets have access to the same automatically defined variables as expressions

  16. Scriptlet Translation <%= foo() %> <% bar(); %> public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... response.setContentType("text/html"); ... out.print(foo()); bar(); ... }

  17. An Interesting Example Scriptlets don't have to be complete code blocks: <%if (Math.random() < 0.5) { %> You <B>won</B> the game! <%} else { %> You <B>lost</B> the game! <% } %> if (Math.random() < 0.5) { out.write("You <B>won</B> the game!"); } else { out.write("You <B>lost</B> the game!"); }

  18. JSP Declarations • A JSP declaration lets you define methods or members that get inserted into the Servlet class (outside of all methods) • It has the following form: <%! Java Code %> • For example: <%! private int someField = 5; %> <%! private void someMethod(...) {...} %> • It is usually of better design to define methods in a separate Java class...

  19. Declaration Example • Print the number of times the current page has been requested since the server booted (or the Servlet class was changed and reloaded): <%! private int accessCount = 0; %> <%! private synchronized int incAccess() { return ++accessCount; } %> <H1>Accesses to page since server reboot: <%= incAccess() %> </H1>

  20. public class serviceCount_jsp extends... implements... throws... { private int accessCount = 0; private synchronized int incAccess() { return ++accessCount;} public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... ... out.write("<H1>Accesses to page since server reboot: "); out.print(incAccess()); ... } ... }

  21. jspInit and jspDestroy • In JSP pages, like regular Servlets, sometimes want to use init and destroy • It is illegal to use JSP declarations to override init or destroy, since they (usually) are already implemented by the generated Servlet • Instead, override the methods jspInit and jspDestroy • The generated servlet is guaranteed to call these methods from init and destroy respectively • The standard versions of jspInit and jspDestroy are empty (placeholders for you to override)

  22. JSP Directives • A JSP directive affects the structure of the Servlet class that is generated from the JSP page • It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive can be combined: <%@ directive attribute1="value1" ... attributeN="valueN" %> • Two types discussed in this section: page and include

  23. page-Directive Attributes • importattribute: A comma separated list of classes/packages to import <%@ page import="java.util.*, java.io.*" %> • contentTypeattribute:Sets the MIME-Type of the resulting document (default is text/html) <%@ page contentType="text/plain" %> • Note that instead of using the contentType attribute, you can write <% response.setContentType("text/plain"); %>

  24. More page-Directive Attributes • session="true|false" - use a session? • buffer="sizekb|none" • Specifies the content-buffer size (out) • errorPage="url " • Defines a JSP page that handles uncaught exceptions • The page in url must have true in the page-directive: • isErrorPage="true|false" • The variable exception holds the exception thrown by the calling JSP

  25. showTableA.jsp <HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page import="java.sql.*" %> <%@ page errorPage="errorPage.jsp" %> <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:" + "snoopy/snoopy@sol4:1521:stud"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from a"); ResultSetMetaData md = rs.getMetaData(); int col = md.getColumnCount(); %>

  26. <TABLE border="2"> <% while (rs.next()) { %> <TR> <% for (int i = 1 ; i <= col ; i++) { %> <TD><%= rs.getString(i) %></TD> <% } %> </TR> <% } %> </TABLE> </BODY> </HTML>

  27. errorPage.jsp <HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page isErrorPage="true" %> <h1>Oops. There was an error when you accessed the database. </h1> <h2>Here is the stack trace: </h2> <font color="red"> <pre> <% exception.printStackTrace(new PrintWriter(out)); %> </pre></font> </BODY> </HTML>

  28. Table A exists!

  29. Table A does not exist!

  30. The include Directive • This directive lets you include files at the time the JSP page is translated into a Servlet • The directive looks like this: <%@ include file="url" %> • JSP content can affect main page • In Tomcat 5.x, generated Servlet is updated when included files change (unlike old versions...)

  31. <HTML> <HEAD> <TITLE>Including JSP</TITLE></HEAD> <BODY> Here is an interesting page.<br><br> Bla, Bla, Bla, Bla. <br><br><br> <%@ include file="AccessCount.jsp"%> </BODY> </HTML> BlaBla.jsp <hr> Page Created for Dbi Course. Email us <a href="mailto:dbi@cs.huji.ac.il">here</a>. <br> <%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %> AccessCount.jsp

  32. out.write("<HTML> \r\n"); out.write("<HEAD> <TITLE>Including JSP</TITLE></HEAD>\r\n"); out.write("<BODY>\r\n"); out.write("Here is an interesting page.<br><br>\r\n"); out.write("Bla, Bla, Bla, Bla. <br><br><br>\r\n"); out.write("\r\n"); out.write("<hr>\r\n"); out.write("Page Created for Dbi Course. Email us \r\n"); out.write("<a href=\"mailto:dbi@cs.huji.ac.il\">here</a>.\r\n"); out.write("<br>\r\n"); out.write(" \r\n"); out.write("Accesses to page since server reboot: \r\n"); out.print( ++accessCount ); out.write("\r\n"); out.write("</BODY>\r\n"); out.write("</HTML> ");

  33. Writing JSP in XML(and vice versa) • We can replace the JSP tags with XML tags that represent • Expressions • Scriptlets • Declarations • Directives

  34. <jsp:expression> Expression </jsp:expression> <%=Expression%> <jsp:scriptlet> Code </jsp:scriptlet> <% Code %> <jsp:declaration> Declaration </jsp:declaration> <%! Declaration %> <jsp:directive.type Attribute="value"/> <%@ Directive %>

  35. <?xml version="1.0" encoding="UTF-8"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <numbers> <jsp:scriptlet> for(int i=1; i&lt;=10; ++i) { </jsp:scriptlet> <number> <jsp:expression> i </jsp:expression> </number> <jsp:scriptlet> } </jsp:scriptlet> </numbers> </jsp:root>

  36. Variables in JSP

  37. Implicit Objects • As seen before, some useful variables, like request and session are predefined • These variables are called implicit objects • Implicit objects are defined in the scope of the service method • Can these be used in JSP declarations? • Implicit objects are part of the JSP specifications

  38. The objects request and response • request and response are the HttpServletRequest and HttpServletResponse arguments of the service method • Using these objects, you can: • Read request parameters • Set response headers • etc. (everything we learned in Servlet lectures)

  39. The object out • This is the Writerused to add write output into the response body • This object implements the interface JspWriter, which supports auto-flush • Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute of the page directive

  40. The object page • Simply a synonym for (Object)this • page is not very useful in JSP pages • It was created as a placeholder for the time when the scripting language could be something other than Java

  41. The object pageContext • pageContext is a new object introduced by JSP • This object encapsulates use of server-specific features (e.g. higher performance JspWriters) • Access server-specific features through this class rather than directly, so your code will conform to JSP spec. and not be server dependent • This object is also used to store page-scoped Java Beans (discussed later)

  42. The object session • This is the HttpSession object associated with the request • If the session attribute in the page directive is turned off (<%@ page session="false" %>) then this object is not available • Recall that a session is created by default

  43. The object config • This is the ServletConfigof the page, as received in the init() method • Remember: Contains Servlet specific initialization parameters • Later, we will study how initialization parameters are passed to JSP pages in Tomcat • You can get the ServletContext from config

More Related