Your SlideShare is downloading. ×
Java Server Pages
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java Server Pages

3,548
views

Published on

Presentation about JavaServer Pages (JSP).

Presentation about JavaServer Pages (JSP).

Published in: Technology

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,548
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
174
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • ## * * 07/16/96
  • ## * * 07/16/96 * Predefined JSP variables are also known as JSP implicit objects
  • ## * * 07/16/96
  • Transcript

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

    ×