Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java Server Pages


Published on

Presentation about JavaServer Pages (JSP).

Published in: Technology
  • Be the first to comment

Java Server Pages

  1. 1. JavaServer Pages (JSP) Svetlin Nakov Borislava Spasova Creating Dynamic Web Pages
  2. 2. Contents <ul><li>Introduction to JSP Technology </li></ul><ul><li>JSP Expressions </li></ul><ul><li>Predefined JSP Variables </li></ul><ul><li>JSP Scriptlets </li></ul><ul><li>JSP Pages a re Actually Servlets </li></ul><ul><li>JSP Declarations </li></ul><ul><li>JSP Directives </li></ul><ul><ul><li>The JSP @page Directive </li></ul></ul><ul><ul><li>Static and Dynamic Include </li></ul></ul>
  3. 3. Contents (2) <ul><li>More About The JSP Predefined Variables </li></ul><ul><ul><li>Using The &quot; application &quot; Object </li></ul></ul><ul><li>Client and Server Redirection </li></ul><ul><li>HTML Escaping Problems </li></ul>
  4. 4. Introduction to JSP Technology
  5. 5. What is JSP? <ul><li>JavaServer Pages (JSP) is: </li></ul><ul><ul><li>Technology for generating dynamic Web content </li></ul></ul><ul><ul><li>Allows Java programming code to be embedded in the HTML pages </li></ul></ul><ul><ul><li>The Java code is executed on the server during the rendering of the JSP page </li></ul></ul><ul><ul><li>After execution of a JSP page a plain HTML is produced and displayed in the client's Web browser </li></ul></ul>
  6. 6. JSP Technology <ul><li>JSP pages provide an easy way to develop dynamic Web applications </li></ul><ul><ul><li>Operate in a request/response mode </li></ul></ul><ul><ul><ul><li>Like Java servlets </li></ul></ul></ul><ul><ul><li>Generate dynamic content with very little or no coding (for non-programmers) </li></ul></ul><ul><ul><li>Contain HTML text freely mixed with Java code (for advanced programmers) </li></ul></ul><ul><ul><li>Can use various XML tags that simplify development </li></ul></ul>
  7. 7. Date JSP Page – Example <ul><li>Sample JSP page that displays the current date and time </li></ul><html> <head><title>Date JSP example </title></head> <body> The date is: <% out.println(new java.util.Date()); %> </body> </html> date.jsp
  8. 8. JSP Expressions <ul><li>A JSP expression is used to insert the result of a Java expression directly into the output </li></ul><ul><li>It has the following form: </li></ul><ul><li>Examples: </li></ul><%= Java e xpression %> The time is : <%= new java.util.Date() %> The square root of 2 is : <%= Math.sqrt(2) %> The value of PI is: <%= Math.PI %>
  9. 9. Predefined JSP Variables <ul><li>JSP pages support a number of predefined variables that you can use </li></ul><ul><ul><li>request – current HttpServletRequest </li></ul></ul><ul><ul><li>response – the HttpServletResponse </li></ul></ul><ul><ul><li>session – current HttpSession associated with the request (if any) </li></ul></ul><ul><ul><li>out – the text stream for the result of the JSP page ( PrintWriter ) </li></ul></ul><ul><li>These variables are always initialized and can be used in any place in the JSP page </li></ul>
  10. 10. JSP Expressions – More Examples <ul><li>The following example uses the predefined variable request to show the remote host of the client machine: </li></ul><ul><li>Getting the default session timeout </li></ul><ul><li>Getting the client's Web browser identification: </li></ul>Your hostname: <%= request.getRemoteHost() %> Session timeout : <%= session.getMaxInactiveInterval() %> Browser: <%= request.getHeader(&quot;User-Agent&quot;) %>
  11. 11. JSP Scriptlets <ul><li>JSP scriptlets allow Java code to be inserted in the JSP pages </li></ul><ul><li>Scriptlets have access to the automatically defined variables in the JSP pages ( request , response , session , ...) </li></ul><% Java c ode %> <% String queryData = request.getQueryString(); out.println(&quot;Attached GET data: &quot; + queryData); %>
  12. 12. JSP Scriptlets – Example <ul><li>Example of using Java code in a JSP page: </li></ul><ul><li>Example of using loop: </li></ul><% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% } else { %> Have an <B>interesting</B> day! <% } %> <% for (int i=0; i<10; i++) { %> <%= i %> * <%= i %> = <%= i*i %> <br> <% } %>
  13. 13. JSP Internals How JSP Pages Are Transformed to Servlets?
  14. 14. JSP Technology Internals <ul><li>JSP pages are actually servlets! </li></ul><ul><ul><li>The Web container translates JSP pages into Java servlet source code ( .java ) </li></ul></ul><ul><ul><li>Then compiles that class into Java servlet class </li></ul></ul><ul><li>JSP pages have the same life cycle like servlets </li></ul>JSP Page ( date .jsp ) Java servlet ( date .java ) Compiled Java servlet ( date . class ) JSP compiler javac
  15. 15. JSP Technology Internals <ul><li>Tomcat stores the compiled JSP pages in the directory CATALINA_HOME/work </li></ul><html> <head><title>Date JSP example</title></head> <body> The date is: <% out.println(new java.util.Date()); %> </body> </html> date.jsp JSP compilation package org.apache.jsp; public final class date_jsp extends HttpJspBase implements JspSourceDependent { ... } webappsJSP-Demos date.jsp workCatalinalocalhost JSP-Demosorgapachejsp
  16. 16. JSP Declarations and Directives
  17. 17. JSP Declarations <ul><li>A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class </li></ul><ul><ul><li>It has the following form: </li></ul></ul><ul><li>Example: </li></ul><%! Java c ode (fields and methods) %> <%! long counter = 0; public void getCounter() { return counter; } %>
  18. 18. JSP Declarations <ul><li>Declarations do not generate any output </li></ul><ul><ul><li>Normally are used in conjunction with JSP expressions or scriptlets </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>Printing how many times a page is displayed since its loading on the server: </li></ul></ul><%! private static int accessCount = 0; %> This page has been accessed <%= ++accessCount %> times.
  19. 19. JSP Directives <ul><li>A JSP directive affects the overall structure of the servlet class </li></ul><ul><ul><li>Usually has the following form: </li></ul></ul><ul><li>Or have multiple attributes: </li></ul><%@ directive attribute=&quot;value&quot; %> <%@ directive attribute1=&quot;value1&quot; attribute2=&quot;value2&quot; ... attributeN=&quot;valueN&quot; %>
  20. 20. The JSP @ page Directive <ul><li>The page directive lets you define one or more page attributes: </li></ul><ul><ul><li>Specifying what packages should be imported </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><li>The import attribute is the only one that is allowed to appear multiple times </li></ul></ul>import=&quot;package.class &quot; or import=&quot;package.class1, ..., package.classN&quot; <%@ page import=&quot;java.util.*&quot; %>
  21. 21. The JSP @ page Directive (2) <ul><li>Specifying the MIME type of the output (the default is &quot;text/html&quot;) </li></ul><ul><li>For example, the directive: </li></ul><ul><li>has the same effect as the scriptlet: </li></ul>contentType=&quot;MIME-Type&quot; or contentType=&quot;MIME-Type; charset=Character-Set&quot; <%@ page contentType=&quot;text/plain&quot; %> <% response.setContentType(&quot;text/plain&quot;); %>
  22. 22. The JSP @ page Directive (3) <ul><li>Defining whether the page will use the implicit session object (default is true) </li></ul><ul><li>Defining an URL to the page to which all uncaught exceptions should be sent </li></ul><ul><li>Declaring the current page as error page (allows access to the exception object) </li></ul>session=&quot;true|false&quot; errorPage=&quot;url&quot; isErrorPage=&quot;true|false&quot;
  23. 23. The JSP @ include Directive <ul><li>Lets you include files at the time the JSP page is translated into a servlet (also called static include ) </li></ul><ul><li>The directive looks like this: </li></ul><ul><ul><li>The URL specified is interpreted as relative to the JSP page that refers to it </li></ul></ul><ul><li>Example: </li></ul><%@ include file=&quot;relative url&quot; %> <%@ include file=&quot;/ include/ menu.jsp&quot; %>
  24. 24. Using JSP @ include Directive <ul><li>Using the @include directive to include a small navigation bar on each page </li></ul>< html > < body > <%@ include file=&quot;/navbar.html&quot; %> <!-- Part specific to this page ... --> </ body > </ html >
  25. 25. Dynamic Include <ul><li>Including a page at runtime ( dynamic include ): </li></ul><ul><li>Dynamic include executes the page at runtime and appends the results of it </li></ul><ul><li>More powerful and flexible </li></ul><jsp:include page=&quot;header.jsp&quot; /> <% String headerPage = &quot;header.jsp&quot; ; %> <jsp:include page=&quot;<%= headerPage %>&quot; />
  26. 26. JSP Predefined Variables request , response , session , application , config , …
  27. 27. More About The JSP Predefined Variables <ul><li>request </li></ul><ul><ul><li>The HttpServletRequest associated with the request </li></ul></ul><ul><ul><li>Allows accessing the request parameters, HTTP headers, cookies, etc. </li></ul></ul><ul><li>response </li></ul><ul><ul><li>The HttpServletResponse associated with the response to the client </li></ul></ul><ul><ul><li>It is legal to set HTTP status codes and response headers (because the output stream is buffered) </li></ul></ul>
  28. 28. More About The JSP Predefined Variables (2) <ul><li>out </li></ul><ul><ul><li>The PrintWriter used to send text output to the client </li></ul></ul><ul><li>session </li></ul><ul><ul><li>The HttpSession object associated with the request </li></ul></ul><ul><ul><li>Sessions are created automatically, so this variable is bound even if there was no incoming session reference </li></ul></ul><ul><ul><li>Can store state information about the current client </li></ul></ul>
  29. 29. More About The JSP Predefined Variables (3) <ul><li>application </li></ul><ul><ul><li>The ServletContext as obtained via getServletConfig().getContext() </li></ul></ul><ul><ul><li>Can store information accessible from whole the application </li></ul></ul><ul><ul><li>All servlets and JSP pages can share information through this object </li></ul></ul><ul><li>pageContext </li></ul><ul><ul><li>Encapsulates all other implicit JSP objects ( request , response , session , ...) in a PageContext instance </li></ul></ul>
  30. 30. More About The JSP Predefined Variables (4) <ul><li>page </li></ul><ul><ul><li>Synonym of this object (not very useful) </li></ul></ul><ul><li>exception </li></ul><ul><ul><li>The implicit Throwable object </li></ul></ul><ul><ul><li>Available only in the error pages </li></ul></ul><ul><ul><li>Contains the last exception </li></ul></ul><ul><li>config </li></ul><ul><ul><li>Contains the ServletConfig for the current JSP page </li></ul></ul><ul><ul><li>Useful for accessing the init parameters </li></ul></ul>
  31. 31. Using The application Object <ul><li>Always use the application object in a synchronized section </li></ul><ul><ul><li>It is shared object between all threads </li></ul></ul><ul><ul><li>Web containers run a separate thread for each client request </li></ul></ul>synchronized (application) { Vector items = (Vector) application.getAttribute (&quot;items&quot;); if (sharedItems == null) { sharedItems = new Vector (); application.setAttribute (&quot;items&quot;, items); } }
  32. 32. Using The application Object – Example <%@ page import=&quot;java.util.Vector&quot; %> <%// Get the global list of shared items Vector<String> sharedItems; synchronized (application) { sharedItems = (Vector<String>) application.getAttribute (&quot;items&quot;); if (sharedItems == null) { sharedItems = new Vector<String>(); application.setAttribute (&quot;items&quot;, sharedItems); } } // Append the new item (if exists) String newItem = request.getParameter(&quot;item&quot;); if (newItem != null) sharedItems.addElement(newItem); %>
  33. 33. Using The application Object – Example (2) <html> <head><title>Global Shared List</title></head> <body> Available shared items: <ol> <% for (String item : sharedItems) { %> <li><%= item %></li> <% } %> </ol> <form method=&quot;POST&quot; action=&quot;Global-Shared-List.jsp&quot;> <input type=&quot;text&quot; name=&quot;item&quot;> <input type=&quot;submit&quot; value=&quot;Add&quot;> </form> </body> </html>
  34. 34. Client and Server Redirections
  35. 35. Client Redirection to Another URL <ul><li>Client redirection </li></ul><ul><ul><li>Redirects the client's Web browser to given new relative URL </li></ul></ul><ul><ul><li>Actually sends HTTP response code 302 ( Resource moved temporarily ) </li></ul></ul><ul><ul><li>The browser requests the new location </li></ul></ul><ul><li>Example: </li></ul>response.sendRedirect(<url>); response.sendRedirect(&quot;date.jsp&quot;);
  36. 36. Server Redirection to Another Resource <ul><li>Server redirection </li></ul><ul><ul><li>Returns the contents of given resource at the server </li></ul></ul><ul><ul><li>The browser does not know that a redirection is occurred at the server </li></ul></ul><ul><li>Example: </li></ul>request.getRequestDispatcher(<url>). forward(request, response) request.getRequestDispatcher(&quot;date.jsp&quot;). forward(request, response);
  37. 37. <jsp:forward> <ul><li>Forwards a client request to an HTML file, JSP file, or servlet for processing </li></ul><ul><ul><li>Simple s yntax </li></ul></ul><ul><ul><li>Syntax with parameters </li></ul></ul><jsp:forward page= {&quot; relativeURL &quot; | &quot;<%= expression %>&quot;} /> <jsp:forward page={&quot; relativeURL &quot; | &quot;<%= expression %>&quot;} > <jsp:param name=&quot; parameterName &quot; value=&quot;{ parameterValue | <%= expression %>}&quot; /> </jsp:forward>
  38. 38. <jsp:forward> – Example <ul><li>Example: </li></ul><ul><li><jsp:forward> actually performs a server-side redirection </li></ul><ul><ul><li>The client does not know that a redirection has occurred </li></ul></ul><jsp:forward page=&quot;Global-Shared-List.jsp&quot;> <jsp:param name=&quot; item &quot; value= &quot;This item is added by JSP-forward.jsp&quot; /> </jsp:forward>
  39. 39. Escaping Problems And How to Avoid Them
  40. 40. Escaping Problems <ul><li>Escaping problems are very common in the Web programming </li></ul><ul><ul><li>Displaying not escaped text is dangerous </li></ul></ul><ul><ul><ul><li>Makes the application unstable </li></ul></ul></ul><ul><ul><ul><li>Opens security vulnerabilities </li></ul></ul></ul><ul><li>When displaying text it should not contain any HTML special characters </li></ul><ul><ul><li>Performing escaping of the HTML entities is obligatory! </li></ul></ul>
  41. 41. Escaping Problems – Example <ul><li>Consider the following JSP page: </li></ul><ul><li>What will happen if we enter this? </li></ul><html> You entered: <%= request.getParameter(&quot;something&quot;) %> <form> Enter something:<br> <input type=&quot;text&quot; name=&quot;something&quot;> <input type=&quot;submit&quot;> </form> </html> <script language=&quot;JavaScript&quot;>alert('Bug!');</script>
  42. 42. What To Escape? <ul><li>What symbols to escape depends on the place where we put the escaped text: </li></ul><ul><ul><li>In the HTML document body dangerous characters are: </li></ul></ul><ul><ul><ul><li>< , > , & , space (and maybe tab , new line ) </li></ul></ul></ul><ul><ul><li>Inside an attribute of a HTML tag the dangerous characters are: </li></ul></ul><ul><ul><ul><li>&quot; and & </li></ul></ul></ul><ul><ul><li>Inside a <textarea> we need to escape: </li></ul></ul><ul><ul><ul><li>< , > and & </li></ul></ul></ul>
  43. 43. Escape The HTML Special Characters <ul><li>Generally we should always escape the following HTML special characters: </li></ul><ul><li>In the HTML body we may need to escape also: </li></ul>&quot; &quot; Quotation Mark & &amp; Ampersand > &gt; Greater Than < &lt; Less Than Character HTML Entity Character Name &nbsp;&nbsp;&nbsp; &nbsp; Tab <br> New Line &nbsp; Space Escaping Character Name
  44. 44. HTML Escaping <ul><li>There is no standard method in Servlet/JSP API for HTML escaping </li></ul><ul><li>We need a custom escaping method: </li></ul>public static String htmlEscape(String text) { if (text == null) { return &quot;&quot;; } StringBuilder escapedText = new StringBuilder(); for (int i=0; i<text.length(); i++) { char ch = text.charAt(i);
  45. 45. HTML Escaping (2) if (ch == '<') escapedText.append(&quot;&lt;&quot;); else if (ch == '>') escapedText.append(&quot;&gt;&quot;); else if (ch == '&') escapedText.append(&quot;&amp;&quot;); else if (ch == '&quot;') escapedText.append(&quot;&quot;&quot;); else escapedText.append(ch); } String result = escapedText.toString(); return result; }
  46. 46. Problems <ul><li>Create a JSP page that calculates the sum of 2 integer numbers. The page should have two form fields and a submit button. </li></ul><ul><li>Create a JSP page that can add an remove items. The items are strings and should be stored in the client's session. </li></ul><ul><li>Using the JSP dynamic include create a small web site (2-3 pages) that has header, footer and a menu on each page. The header contents, footer contents and the menu should be placed in separate files. </li></ul>
  47. 47. Problems (2) <ul><li>Using the global application object implement a counter of the visitors of the site. </li></ul><ul><li>Using the client's session object and the client redirection technique implement a JSP page that enters an integer number sequentially 5 times. After the entering the 5th number the client's Web browser should be redirected to another JSP page that shows all entered numbers and their sum. </li></ul><ul><li>Ensure that no escaping problems are present in all your previous JSP pages. Correct them as needed. </li></ul>
  48. 48. Homework <ul><li>Using the global application object implement the &quot;number guess game&quot; that can be played globally by multiple players in the same time. </li></ul><ul><li>The number guess game starts with a secret number randomly chosen by the server. Each player can make guesses and the server tells whether the number is smaller, larger or the same. </li></ul><ul><li>The player who first guesses the number wins and the game starts again. </li></ul>
  49. 49. Homework (2) <ul><li>Using the JSP technology implement a simple discussion forum. Each visitor should be able to post new topics, to reply to a topic and to delete topics and replies. Each topic is a message and can have replies. The replies are messages in the same topic (no nesting is allowed). Each message consists of author subject and contents. </li></ul><ul><li>Each page in the forum should have a header, a footer and a menu (implemented by including fragments of JSP pages). </li></ul><ul><li>Take care of possible escaping problems. </li></ul>