Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JSP – Java Server Pages Part 1 Representation and Management of Data on the Internet Sun JSP Tutorial 1 Introduction 2 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...") 3 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.5, you can find the generated Servlet code under $CATALINA_BASE/work/ 4 Relationships • Servlets: HTML code is printed in Java code • JSP: Java code is embedded in HTML code Java HTML HTML Java 5 Example <html> <head> <title>Hello World</title> </head> <body> <h2><%= new java.util.Date() %></h2> <h1>Hello World</h1> </body> </html> Open the generated Java code 6 Generated Servlet Hierarchy (Tomcat 5.0 Implementation) Sun Specifications Servlet classes GenericServlet HttpServlet Apache Implementation Abstract class extended by every generated Servlet JspPage interfaces HttpJspPage HttpJspBase mypage_jsp Generated Servlet Read more about Apache HttpJspBase Class 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 JSP Life Cycle 9 JSP Life Cycle The following table describes the life cycle of JSP generated Servlet in details: 10 Translation & compilation only after first call… JSP Life Cycle Request #3 Request #4 Request #5 Request #6 Yes No No No Yes No Yes No No No Yes No Yes No Yes No Yes No init (or equivalent) called Yes No Yes No Yes No doGet (or equivalent) called Yes Yes Yes Yes Yes Yes JSP page translated into servlet Servlet instantiated and loaded into server's memory Page first written JSP’s Servlet compiled Page modified Request #2 Server restarted Request #1 Written by Marty Hall. Core Servlets & JSP book: www.coreservlets.com 11 JSP Translation • When the JSP file is modified, JSP is translated into a Servlet JSP file named file.jsp will be translated into the Java file file_jsp.java - But only after the JSP’s url is requested by the client - Application needs not be reloaded when JSP file is modified • Server does not generate the Servlet class after startup, if the latter already exists - Generated Servlet acts just like any other Servlet • The generated servlet can handle GET, POST, HEAD requests though it does not implement doGet(), doPost(), doHead() explicitly - Its Servlet.service() method calls the newly implemented main method named HttpJspBase._jspService() 12 init() and destroy() • init() of the generated Servlet is called every time the Servlet class is loaded into memory and instantiated • destroy() of the generated Servlet is called every time the generated Servlet is removed • The latter two happen even if the reason is modification of the JSP file 13 jspInit and jspDestroy • In JSP pages, like regular Servlets, we sometimes want to implement init and destroy • It is illegal to use JSP declarations to override init or destroy, since they are (usually) 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) 14 Thread Synchronization • After the Servlet is generated, one instance of it serves requests in different threads, just like any other Servlet • In particular, the service method (_jspService) may be executed by several concurrent threads • Thus, like Servlets, JSP programming requires concurrency management 15 Basic JSP Elements A Quick Reference to JSP Elements 16 Basic Elements in a JSP file • HTML code: <html-tag>content</html-tag> • JSP Comments: <%-- comment --%> • Expressions: <%= expression %> • Scriptlets: <% code %> • Declarations: <%! code %> • Directives: <%@ directive attribute="value" %> • Actions: <jsp:forward.../>, <jsp:include.../> • EL Expressions: ${expression} Covered Later... 17 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: The heading space and the following space are not created in the result. Use “ “ if you want a real space <%= new java.util.Date() %> <%= "Hello"+" World" %> <%= (int)(100*Math.random()) %> 18 JSP Expressions • Within the generated Java code - 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... 19 Expression Translation <h1>A Random Number</h1> <%= Math.random() %> public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { ... Default contentresponse.setContentType("text/html"); type ... out.write("<h1>A Random Number</h1>\r\n"); out.print( Math.random() ); The generated servlet out.write("\r\n"); calls out.write() for Strings, and out.print() ... for objects 20 } 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 - config: The ServletConfig • These variables and more will be discussed in details 21 <html> <head> <title>JSP Expressions</title> </head> <body> <h2>JSP Expressions</h2> <ul> <li>Current time: <%= new java.util.Date() %></li> <li>Your hostname:<%= request.getRemoteHost() %></li> <li>Your session ID: <%= session.getId() %></li> <li>The <code>testParam</code> form parameter: <%= request.getParameter("testParam") %></li> </ul> </body> Computer-code style </html> 22 JSP Scriplets • JSP scriptlets let 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 scriptlet • Scriptlets have access to the same automatically defined variables as expressions 23 Scriptlet Translation <%= foo() %> <% bar(); %> public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... response.setContentType("text/html"); ... out.print(foo()); bar(); ... } 24 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!"); } 25 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... 26 Declaration Example • Print the number of times the current page has been requested since the Servlet initialization: <%! private int accessCount = 0; %> <%! private synchronized int incAccess() { return ++accessCount; } %> <h1>Accesses to page since Servlet init: <%= incAccess() %> </h1> 27 public class serviceCount_jsp extends... implements...Generated Servlet throws... { Java permits private int accessCount = 0; member initialization on private synchronized int incAccess() { declaration, even if the location is return ++accessCount; outside any } method’s scope public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... ... out.write("<h1>Accesses to page since Servlet init: "); out.print(incAccess()); ... } ... } 28 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 attribute1="value1" ... attributeN="valueN" %> • Three important directives: page, include and taglib • include and taglib will be discussed later 29 page-Directive Attributes • import attribute: A comma separated list of classes/packages to import <%@ page import="java.util.*, java.io.*" %> Imports from the class/Jar locations as mentioned in Tomcat class • contentType attribute: Sets the MIME-Type of the resulting document (default is text/html as already mentioned) <%@ page contentType="text/plain" %> 30 page-Directive Attributes (cont) • What is the difference between setting the page contentType attribute, and writing <%response.setContentType("...");%> ? - In the latter case, the new servlet will call response.setContentType() twice - First time would be created implicitly with the default content type - Second type is the explicit call and might be written within the generated Servlet after the out buffer was already flushed… - The explicit call (as opposed to the implicit one) might even come after the buffer was flushed or after the writer was obtained Check: double-contenttype.jsp code using the explicit call, generated java code (servlet) 31 page-Directive Attributes (cont) • session="true|false" - use a session? The underlined value is the default • buffer="sizekb|none|8kb" . If the JSP is defined as using a session, a session cookie will be sent to the client - Specifies the content-buffer (out) size in kilo-bytes • autoFlush="true|false" - Specifies whether the buffer should be flushed when it fills, or throw an exception otherwise • isELIgnored ="true|false" - Specifies whether JSP expression language is used - EL is discussed later 32 Variables in JSP 33 Implicit Objects • As seen before, some useful variables, like request and session are predefined • These variables are called implicit objects • Implicit objects are part of the JSP specifications • Implicit objects are defined in the scope of the service method - Can these be used in JSP Declarations? - What about redefinitions within JSP Scriptlets? Check the result of : no-redefinition, redefinition within a Declaration, redefrinition within a Scriptlet 34 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) Read more about HttpServletRequest Interface, HttpServletResponce Interface 35 The object out • This is the Writer used to add write output into the response body • This object implements the interface JspWriter that combines the functionality of PrintWriter and BufferedWriter • Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute But again just like in response of the page directive and ContentType, a better solution is to use the page directive Read more about JspWriter Class 36 The object pageContext • pageContext is a new object introduced by JSP • This object stores all important elements used by the generated Servlet, like the application context, the session, the output writer, etc. • It enables vendors to extend their JSP implementation - E.g. Apache could extend the PageContext class so it’ll store some additional application context, extend HttpJspBase class so that the new PageContext could be obtained … • This object is also used to store page-scoped attributes (e.g., Java Beans - discussed later) • This object is a field of Apache’s HttpJspBase class Read more about PageContext Class 37 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 Check the result of using a session after defining “no session” Read more about HttpSession Interface 38 The object config • This is the ServletConfig of 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 • Recall that you can also obtain the ServletContext from config as explained in the next slide… Read more about ServletConfig Interface 39 The object application • This is the ServletContext as obtained via getServletConfig().getContext() • Remember: - The ServletContext is shared by all Web-application Servlets (including ones generated from JSP) - Getting and setting attributes is with getAttribute and setAttribute of ServletContext - You can use this object to get application-wide initialization parameters Read more about ServletContext Interface 40 That is a specific thread of execution Page Scope Variables e.g. defined within Scriptlets e.g. objects set using pageContext.setAttribute() • service() local variables • pageContext attributes a.jsp client 1 Matches a 1:1 connection between JSPs and Clients b.jsp The JSPs resides the same application in those examples client 2 41 Request Scope • request attributes A more complex scenario in which the request is forwarded to another JSP A simple scenario a.jsp a.jsp client 1 client 1 b.jsp b.jsp client 2 client 2 42 Session Scope Many JSPs (belong to the same application) to a single Client • session attributes e,g. set with session.setAttribute() a.jsp client 1 b.jsp client 2 Run http://localhost/test1/test1.jsp Conclude that there is a different session for every application. 43 e.g. defined within Declarations. The class members are indeed having the same values for all clients since there’s a single instance of this class Servlet Scope • Servlet members a.jsp client 1 Possibly a single JSP to many Clients b.jsp client 2 44 Application Scope • application attributes e.g. defined within application.setAttribute() a.jsp client 1 Possibly many JSPs to many Clients b.jsp client 2 45 Servlet Package and Helper Classes • The generated Servlet has a named package • In Tomcat, this package is: org.apache.jsp • In Java, you cannot use classes from the default package (i.e. with no package declaration) from a named package! • Therefore, helper classes used by JSP pages must have a named package For example, classes which are imported using the PAGE directive 46 Using External Parameters 47 JSP Initial Parameters • Like Servlets, initialization parameters can be passed to JSP files using the <servlet> element of the application configuration file web.xml • Use the sub-element <jsp-file> instead of the sub-element <servlet-class> • Since <servlet> element is being used, a <servlet-mapping> element is also needed - Use the real JSP URL as the <jsp-file> 48 An Example Application scoped initialization parameters web.xml <web-app> <context-param> <param-name>dbLogin</param-name> <param-value>snoopy</param-value> </context-param> <context-param> <param-name>dbPassword</param-name> <param-value>snoopass</param-value> </context-param> 49 web.xml <servlet> <servlet-name>ParamPage</servlet-name> timescoped the relative <jsp-file>/paramPage.jsp</jsp-file> ThisJSP location of the JSP initialization <init-param> (relative to the parameters application’s root <param-name>tableName</param-name> directory) should be <param-value>users</param-value> given instead of the Servlet classname </init-param> since there’s no default location for </servlet> JSP resources <servlet-mapping> <servlet-name>ParamPage</servlet-name> <url-pattern>/paramPage.jsp</url-pattern> Of course you can map </servlet-mapping> a different URL to this </web-app> JSP 50 paramPage.jsp <html> You can omit the <head><title>JSP initial parameters</title></head> config and call getInitParameter() <body> directly, since the JSP scope <h1>Hello</h1> generated servlet extends <h2>I should use the table HttpJspBase which HttpServlet <i><%= config.getInitParameter("tableName")extends %></i> that implements the </h2> ServletConfig <h2>To access the Database, I should use the logininterface <i><%= application.getInitParameter("dbLogin") %></i> and the password <i><%= application.getInitParameter("dbPassword") %></i>. </h2> Equivalent to Application scope </body> getServletContext().getInitParameter() in Servlets </html> 51 JSP and XML 52 Simple XML Production Ordinary Link with XML XSL declarations stylesheet <?xml version="1.0"?> <!DOCTYPE colors SYSTEM "colors.dtd"> <?xml-stylesheet type="text/xsl" href="colors.xsl"?> <%! static String[] colors = {"red","blue","green"}; %> <%@ page contentType="text/xml" %> JSP directive which <colors> sets the MIME-type of the result… <% for(int i=0; i<3; ++i) { %> <color id="<%=i%>"><%= colors[i] %></color> <% } %> Open colors.jsp Check the result of the same JSP without the page </colors> contentType directive 53 Generated XML <?xml version="1.0"?> <!DOCTYPE colors SYSTEM "colors.dtd"> <?xml-stylesheet type="text/xsl" href="colors.xsl"?> <colors> <color id="0">red</color> <color id="1">blue</color> <color id="2">green</color> </colors> 54 JSPX Files (JSP Documents) • JSPX files are JSP files that have the extension jspx and have XML syntax • JSPX files are also referred to as JSP documents • Non-XML symbols <%, <%@, etc. are replaced with special JSP tags • Default content type of JSPX is text/xml (and not text/html) Sun JSP Documents Tutorial 55 Advantages in JSPX • Since they conform a legal XML structure you can - Check if the document is well formed XML - Validate the document against a DTD - Nest and scope namespaces within the document - Use all kinds of XML tools (e.g. editors) 56 <%= Expression %> <jsp:expression> Expression </jsp:expression> <% Code %> <jsp:scriptlet> Code </jsp:scriptlet> <%! Declaration %> <jsp:declaration> Declaration </jsp:declaration> An empty element <%@ Directive %> <jsp:directive.type Attribute="value"/> 57 Problems with JSPX • The XML declaration (<?xml version="1.0"?>) and the DOCTYPE definition are now those of the JSPX file. - How do we include the declaration+dtd of the original XML document in the result XML? - Solution: use the <jsp:output> tag to explicitly require DOCTYPE and XML declarations (next slide…) • How do we generate dynamic attribute values and still keep the document well formed? The following line is illegal XML opening tag: <color id=“<jsp:expression>i</jsp:expression>“> - Solution 1: use <jsp:element> for explicit element construction - Solution 2: use an EL expression (discussed later) 58 <colors xmlns:jsp="http://java.sun.com/JSP/Page"> Adding XSL declaration is hard since it should be <jsp:output doctype-root-element="colors" Noticethe thatroot there is no outside element doctype-system="colors.dtd" /> page directive with CDATA section must This namespace is be (colors) but after Adding DTD, however, is contentType=“text/xml” used since the text Root important Do element not omit for the + the DTD using XML of of the jsp:output which must be <jsp:output omit-xml-declaration="false"/> attribute possible but harder, since Ofcontains course we could add since this is JSPX illegal XML basic declaration resulting JSP should elements ofXML the result and defined after jsp the DTD enable <?xml version=“1.0” ?> file and itslibraries.. default output <jsp:declaration>static String[] colors = {"red","blue","green"}; Tag syntax (e.g. < ). namespace declaration every JSP element within type is XML You within canother use the < colors instead every element </jsp:declaration> of using element… the CDATA <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet> block <jsp:element name="color"> <jsp:attribute name="id"> <jsp:expression>i</jsp:expression> </jsp:attribute> <jsp:expression>colors[i]</jsp:expression> </jsp:element> <jsp:scriptlet>} The result is equivalent to the original line: </jsp:scriptlet> <color id="<%=i%>"><%= colors[i] %></color> </colors> Open colors.jspx, result of the same JSP with 59 omit-xml-declaration=true (omittruecolors.jspx) JSP as JSPX • You can also keep the JSP suffix and tell the container that a JSP file acts as a JSPX file (and therefore its output is of XML type etc.) • Use the <jsp:root> element as the document root - This element is also useful when using the include directive - While including (without <jsp:root>) the JSP might become illegal XML with more than a single root - The result XML file may still not be well-formed XML with more than a single root 60 <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"> <jsp:output doctype-root-element="colors" doctype-system="colors.dtd" /> <jsp:output omit-xml-declaration="false"/> <![CDATA[<?xml-stylesheet type="text/xsl" href="colors.xsl"?>]]> <colors > Now we can <jsp:declaration>static String[] colors = {"red","blue","green"}; add the XSL </jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet> We use CDATA <jsp:element name="color"> because of the <jsp:attribute name="id"> <jsp:expression>i</jsp:expression></jsp:attribute><?, ?> etc <jsp:expression>colors[i]</jsp:expression> </jsp:element> <jsp:scriptlet>}</jsp:scriptlet> </colors> </jsp:root> Open colors1.2.jsp 61