Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 (Server-Side Programming using Java Server Pages) cs236607.

Similar presentations


Presentation on theme: "1 (Server-Side Programming using Java Server Pages) cs236607."— Presentation transcript:

1 1 (Server-Side Programming using Java Server Pages) cs236607

2 2 Many HTML Pages are Mostly Static 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 very inconvenient to write and maintain long and mostly static HTML pages using Servlets (even though such pages are very common) out.println(" Bla Bla " + "bla bla bla bla" + "lots more here...") cs236607

3 3 Introducing JSP The 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 invokes this servlet In Tomcat 5.5, you can find the generated Servlet code under $CATALINA_BASE/work/ cs236607 A JSP is no more than a convenient way to write Servlets that output textual data

4 4 Relationships Servlets: HTML code is printed using Java code JSP: Java code is embedded in HTML code Not only for HTML! JSP can be used for any textual format Servlets can be used for any data! Java HTML JAVA cs236607

5 5 Example Hello World Hello World cs236607

6 6 The file dates.jsp is in C:\Program Files\Tomcat 5.5\webapps\Examples\ ($CATALINA_BASE\webapps\MyApplication\) The file dates.jsp is in C:\Program Files\Tomcat 5.5\webapps\Examples\ ($CATALINA_BASE\webapps\MyApplication\) The url http://ibm373.cs.technion.ac.il:8080/Examples/dates.jsp The url http://ibm373.cs.technion.ac.il:8080/Examples/dates.jsp

7 Translation to Servlet cs2366077 package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class dates_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static java.util.List _jspx_dependants; public Object getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; C:\Program Files\Tomcat 5.5\webapps\Examples\work\org\apache\jsp\dates_jsp.java

8 cs2366078 try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write(" \r\n"); out.write(" Hello World \r\n"); out.write(" \r\n"); out.write(" "); out.print( new java.util.Date() ); out.write(" \r\n"); out.write(" Hello World \r\n"); out.write(" \r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); }

9 9 Generated Servlet Hierarchy (Tomcat 5 Implementation) Apache Implementation Generated Servlet Sun Specifications classes interfaces Abstract class extended by every generated Servlet cs236607

10 10 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 be created using a "reverse engineering technique": Create static HTML and then replace static data with Java code cs236607

11 11 cs236607

12 12 JSP Life Cycle Request #1 Request #2 Request #3 Request #4 Request #5 Request #6 JSP page translated into servlet YesNo YesNo JSP’s Servlet compiled YesNo YesNo Servlet instantiated and loaded into server's memory YesNoYesNoYesNo init (or equivalent) called YesNoYesNoYesNo doGet (or equivalent) called Yes Written by Marty Hall. Core Servlets & JSP book: www.coreservlets.comwww.coreservlets.com Page first written Server restarted Page modified Translation & compilation only after first call…

13 13 JSP Translation When the JSP file is modified, it is translated into a Servlet But only after the JSP’s url is requested by a client The application is not necessarily reloaded immediately when the JSP file is modified The server does not generate the Servlet class after startup, if the class already exists and is not too old 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() JSP file named file.jsp will be translated into the Java file file_jsp.java cs236607

14 14 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 init() and destroy() are called even when the reason for loading is a modification of the JSP file cs236607

15 15 jspInit and jspDestroy In JSP pages, as in regular Servlets, sometimes we 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) cs236607

16 16 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, as with Servlets, JSP programming requires handling concurrency cs236607

17 17 cs236607

18 18 Basic Elements in a JSP File HTML code: content JSP Comments: Expressions: Scriptlets (statements): Declarations: Directives: Actions:, Expression-Language Expressions: ${expression} cs236607

19 19 JSP Expressions A JSP expression is being used to insert Java values directly into the output It has the form:, 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 cs236607

20 20 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... cs236607

21 21 Expression Translation A Random Number public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {... response.setContentType("text/html");... out.write(" A Random Number \r\n"); out.print( Math.random() ); out.write("\r\n");... } The generated servlet calls out.write() for Strings, and out.print() for objects Default content-type cs236607

22 22 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 cs236607

23 23 JSP Expressions JSP Expressions Current time: Your hostname: Your session ID: The testParam form parameter: cs236607

24 24

25 25 JSP Scriplets (Statements) JSP scriptlets let you insert arbitrary code into the Servlet service method ( _jspService ) Scriptlets have the form: 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 cs236607

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

27 27 A Divided-Code Example Scriptlets do not have to be continuous: You won the game! You lost the game! if (Math.random() < 0.5) { out.write("You won the game!"); } else { out.write("You lost the game!"); } cs236607

28 28 JSP Declarations A JSP declaration lets you define methods or members that are being inserted into the Servlet class (outside of all methods) It has the following form: For example: JSPs are intended to contain a minimal amount of code so it is usually of better design to define methods in a separate Java class... cs236607

29 29 Declaration Example Print the number of times the current page has been requested since the Servlet initialization: <%! private synchronized int incAccess() { return ++accessCount; } %> Accesses to page since Servlet init: cs236607

30 30 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(" Accesses to page since Servlet init: "); out.print(incAccess());... }... } Generated Servlet Java permits variable initialization on declaration, even if the location is outside any method’s scope cs236607

31 31 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: Three important directives: page, include and taglib cs236607

32 32 page -Directive Attributes import attribute: A comma separated list of classes/packages to import contentType attribute: Sets the MIME-Type of the resulting document (default is text/html) cs236607

33 33 page -Directive Attributes (cont) What is the difference between setting the page contentType attribute, and writing ? In the latter case, the new servlet will call response.setContentType() twice The first, impicit (from the JSP point of view), call will be with the default content type. The second, explicit, call might even come after the buffer was flushed or after the writer was obtained… cs236607

34 34 page -Directive Attributes (cont) session="true|false" specifies if to use a session? buffer="sizekb|none|8kb" 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 The underlined values are the defaults cs236607

35 35 cs236607

36 36 JSP Initial Parameters Like Servlets, initialization parameters can be passed to JSP files using the element of the application configuration file web.xml Use the sub-element instead of the sub- element Since a element is being used, a element is also needed Use the real JSP URL as the Remember that just like in servlets mapping, you have the flexibility of being able to map several URLs to the same jsp or servlet, each with different init parameters. cs236607

37 37 dbLogin homer dbPassword doughnuts An Example web.xml Initialization parameters whose scope is application cs236607

38 38 ParamPage /paramPage.jsp tableName users ParamPage /paramPage.jsp web.xml JSP scoped initialization parameters In the case of JSP, the relative location of the JSP (relative to the application’s root directory) should be given instead of the Servlet classname, since the Servlet is created dynamically by the container You can also map a different URL to this JSP (highly useful if you need the URL to end with an extension other than.jsp) cs236607

39 39 JSP initial parameters Hello I should use the table To access the Database, I should use the login and the password. paramPage.jsp JSP scoped initialization parameters Application scoped initialization parameters You can omit the config and call getInitParameter() directly, since the generated servlet extends HttpJspBase which extends HttpServlet which implements the ServletConfig interface Reminder: this is equivalent to getServletContext().getInitParameter() within a Servlet cs236607

40 40 cs236607

41 41 JSP Cooperation We will consider several ways in which JSP and other resources cooperate Forwarding the request handling to other resources Including the content of other sources Including the code of other JSP files Forwarding exception handling to other JSPs cs236607

42 42 Actions JSP actions use constructs in XML syntax to control the behavior of the Servlet engine Using actions, you can forward the request to another resource in the application dynamically include a resource content in the response Forward and include are translated to an invocation of the RequestDispatcher

43 43 The forward Action jsp:forward - Forwards the requester to a new resource }"> <jsp:param name="parameterName" value="{parameterValue | }" /> * You can use %=, % instead of so that the code would be a legal XML 0 or more parameters (not attributes!) added to the original request parameters cs236607

44 44 " /> " /> Forward Action Example cs236607

45 45 Print Request Params : requestParams.jsp cs236607

46 46 The include Action jsp:include - Include a resource content at run time }"> <jsp:param name="parameterName" value="{parameterValue | }" />* 0 or more parameters added to the original request parameters cs236607

47 47 Include (action) Example Included part begins: " /> Included part ends Include Action Example include.jsp cs236607

48 48 : requestParams2.jsp requestParams2.jsp is different from requestParams.jsp in not having the preceding and following html tags (otherwise the output HTML code would have, and duplicated) cs236607

49 49 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: Included JSP content can affect main JSP page e.g. included page directive can affect the result ContentType As of Tomcat 5.x, generated Servlets are updated when included files change (unlike older versions...) cs236607

50 50 Include - Action File1.jsp Servlet1 File2.jsp Servlet2 HTML content HTML content HTML content Using RequestDispatcher Main JSP cs236607

51 51 Include Directive File1.jsp File2.jsp Servlet HTML content cs236607

52 52 include Action vs. Directive When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime (so the resource needs not be a JSP or even a Servlet) When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation (so the included resource must have JSP syntax) In which of the above cases can the included resource change the HTTP headers or status? cs236607

53 53 Including JSP Here is an interesting page. Bla, Bla, Bla, Bla. BlaBla.jsp Accesses to page since Servlet init: Page Created for Simpsons at. Email here. AccessCount.jsp mymail.jsp cs236607

54 54 out.write(" \r\n"); out.write(" Including JSP \r\n"); out.write(" \r\n"); out.write(" Here is an interesting page. \r\n"); out.write(" Bla, Bla, Bla, Bla. \r\n"); out.write(" \r\n"); out.write(" Accesses to page since Servlet init: \r\n"); out.print( ++accessCount ); out.write(" \r\n"); org.apache.jasper.runtime.JspRuntimeLibrary. include(request, response, "/mymail.jsp", out, false); out.write(" \r\n"); BlaBla_jsp.java Original JSP Included JSP Similar to RequestDispatcher().include() Original JSP cs236607

55 55 Error Pages We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives The default behaviour is displaying a 500 Internal Server Error with a partial stack trace with other exception info to the client (ugly and a security risk) You can log the entire stack trace along with other data for easier debugging Defines a JSP page that handles uncaught exceptions The page in url should have true in the page-directive: The variable exception holds the exception thrown by the calling JSP Creating an error page without isErrorPage=true, is legal but the exception object is not created in the generated Servlet. If you refer to exception in such a JSP, you’ll have a compilation error… Runtime exceptions or other exceptions which are declared as thrown by methods your JSP code use. Other exceptions cannot be thrown or else your generated servlet code wouldn’t compile cs236607

56 56 Reading From Database <% Class.forName(“com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection (“jdbc:mysql://ibm262.cs.technion.ac.il:3306/homerDB”, “homer“, “doughnuts”); %> Can Connect!! connect.jsp Reminder: The driver is loaded dynamically Creates an instance of itself Register this instance with the DriverManager cs236607

57 57 Connection Error Oops. There was an error when you accessed the database. Here is the stack trace: errorPage.jsp cs236607

58 Links JSP Tutorial: http://courses.coreservlets.com/Course- Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course- Materials/csajsp2.html Advanced Tutorials: http://courses.coreservlets.com/Course- Materials/msajsp.html http://courses.coreservlets.com/Course- Materials/msajsp.html JSP API: http://tomcat.apache.org/tomcat-5.5- doc/jspapi/http://tomcat.apache.org/tomcat-5.5- doc/jspapi/ JSP Syntax Reference: http://java.sun.com/products/jsp/syntax/2.0/syntaxref 20.html http://java.sun.com/products/jsp/syntax/2.0/syntaxref 20.html cs23660758


Download ppt "1 (Server-Side Programming using Java Server Pages) cs236607."

Similar presentations


Ads by Google