Object-Oriented Enterprise Application Development JavaServer Pages.

63
Object-Oriented Enterprise Application Development JavaServer Pages

Transcript of Object-Oriented Enterprise Application Development JavaServer Pages.

Page 1: Object-Oriented Enterprise Application Development JavaServer Pages.

Object-Oriented Enterprise Application Development

JavaServer Pages

Page 2: Object-Oriented Enterprise Application Development JavaServer Pages.

Topics

During this class we will examine:

Anatomy of a JavaServer Page

Merging markup with Java

Configuring our JSPs with directives

Integrating servlets and JSPs

Page 3: Object-Oriented Enterprise Application Development JavaServer Pages.

JavaServer Pages

Page 4: Object-Oriented Enterprise Application Development JavaServer Pages.

Justification

JavaServer Pages (JSPs) are a technology that allow developers to mix static with dynamic content.

JavaServer Pages have been successful for two (2) reasons:

JSPs are supported across multiple platforms.

JSPs give developers access to all Java technologies instead of using a scripting language.

Page 5: Object-Oriented Enterprise Application Development JavaServer Pages.

Roles and Responsibilities

Although servlets can generate dynamic content, it's often advantageous to separate the business logic in the servlet from the presentation logic.

By using JSPs we can have application programmers building servlets while content designers and graphic artists construct the JSPs.

Page 6: Object-Oriented Enterprise Application Development JavaServer Pages.

Versions

We'll use version 1.1 of the JavaServer Pages specification.

The 1.0 and 1.1 version JSPs are almost totally incompatible with the 0.92 version of the specification.

Page 7: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Structure

Page 8: Object-Oriented Enterprise Application Development JavaServer Pages.

Basic Concepts

At their heart, basic JSPs look just like regular HTML markup.

A static HTML document can be turned into a JSP simply by changing its extension to .jsp.

The key difference is that JSPs are dynamic.

When a JSP is executed, the JSP engine converts that JSP into an equivalent servlet which then follows the normal lifecycle.

Page 9: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - HelloWorld1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <%-- comments look like this --%>3. <HTML>4. <HEAD>5. <TITLE>HelloWorld JSP</TITLE>6. </HEAD>7. <BODY>8. <H2>Hello, World!</H2>9. </BODY>10. </HTML>

Page 10: Object-Oriented Enterprise Application Development JavaServer Pages.

Dynamic Content

If all we needed was static content, then we'd just use HTML. The strength of JSPs lie in their ability to generate and manipulate dynamic content.

There are three common ways of performing this generation using JSPs:

Expressions,

Scriptlets

Declarations

Page 11: Object-Oriented Enterprise Application Development JavaServer Pages.

Lifecycle

Even though JSPs are ultimately compiled into servlets, there are a few differences in their lifecycle.

Most of the tags for generating dynamic content are placed within the JSP's jservice() method.

This method is called by the JSP's service() method for both GET and POST requests.

Page 12: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Tags

Page 13: Object-Oriented Enterprise Application Development JavaServer Pages.

Basic Tags

In the 0.92 version of the JSP specification, we identified dynamic content using special tags.

In version 1.1 of the JSP specification we can still use some of these tags. We can also use equivalent XML tags.

Page 14: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Expressions

The simplest form of dynamic content is the JSP expression. This is used to send a value back to the client.

The tag format of an expression is given by:

<%= java expression %>

Page 15: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - DynamicHelloWorld1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <HTML>3. <HEAD><TITLE>4. DynamicHelloWorld JSP5. </TITLE></HEAD>6. <BODY>7. <H2>Hello, World!</H2><BR>8. <H3>It’s now 9. <%= new java.util.Date() %>10. </H3>11. </BODY>12. </HTML>

Page 16: Object-Oriented Enterprise Application Development JavaServer Pages.

Implicit Variables(1 of 3)

There are eight (8) implicit variables for each JSP. The four (4) most common are:request: The HttpServletRequest object passed to the JSP.

response: The HttpServletResponse object passed to the JSP.

session: The client's HttpSession object.

out: The PrintWriter object used to send output to the client that initiated the request.

Page 17: Object-Oriented Enterprise Application Development JavaServer Pages.

Implicit Variables(2 of 3)

Other useful variables include:application: The ServletContext object.

config: The ServletConfig object.

pageContect: The PageContext object.

page: The this object (not currently used).

Page 18: Object-Oriented Enterprise Application Development JavaServer Pages.

Implicit Variables(3 of 3)

These implicit variable can be used within JSP expressions and scriptlets, but not within JSP declarations.

Page 19: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Status(1 of 2)1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <HTML>3. <HEAD><TITLE>4. StatusHelloWorld JSP5. </TITLE></HEAD>6. <BODY>7. <H2>Hello, World!</H2><BR>8. <H3>Current Time: 9. <%= new java.util.Date() %>10. </H3><BR>11. <H3>Session ID:12. <%= session.getId() %>13. </H3><BR>

Page 20: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Status(2 of 2)14. <H3>Hostname:15. <%= request.getRemoteHost() %>16. </H3><BR>17. <H3>Parameter:18. <%= request.getParameter("test") %>19. </H3>20. </BODY>21. </HTML>

Page 21: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Scriptlets

Often a single expression isn't adequate for the complexity of the output we want the JSP to generate.

JSPs allow us to embed complete segments of Java code within a scriptlet.

The tag format of a scriptlet is given by:

<% java code %>

Page 22: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Scriptlet(1 of 2)1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

Transitional//EN">2. <HTML>3. <HEAD>4. <TITLE>Scriptlet JSP</TITLE>5. </HEAD>6. <BODY>7. <H2>Hello, World!</H2><BR>8. <H3>Current Time:9. <%= new java.util.Date() %>10. </H3><BR>11. <H3>Session ID:12. <%= session.getId() %>13. </H3><BR>

Page 23: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Scriptlet(2 of 2)14. <H3>Hostname:15. <%= request.getRemoteHost() %>16. </H3><BR>17. <%18. String testString =

request.getParameter("test");19. if (null == testString) {20. testString = "no.such.parameter";21. }22. %>23. <H3>Parameter: <%= testString %></H3>24. </BODY>25. </HTML>

Page 24: Object-Oriented Enterprise Application Development JavaServer Pages.

Conditional Tags

JSP scriptlets are useful for including conditional content.

This cuts down on the amount of data returned to the client.

This technique can be used to implement basic security features.

Page 25: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Scriptlet (rev.)(1 of 3)1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <HTML>3. <HEAD>4. <TITLE>Scriptlet JSP</TITLE>5. </HEAD>6. <BODY>7. <H2>Hello, World!</H2><BR>8. <H3>Current Time:9. <%= new java.util.Date() %>10. </H3><BR>

Page 26: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Scriptlet (rev.)(2 of 3)11. <% 12. if (session.getId() != null) { 13. %>14. <H3>Session ID:15. <%= session.getId() %>16. </H3><BR>17. <% 18. } 19. %>20. <H3>Hostname:21. <%= request.getRemoteHost() %>22. </H3><BR>

Page 27: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Scriptlet (rev.)(3 of 3)23. <% 24. String testString =

request.getParameter("test");25. if (null == testString) {26. testString = "no.such.parameter";27. }28. %>29. <H3>Parameter:30. <%= testString %>31. </H3>32. </BODY>33. </HTML>

Page 28: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(1 of 8)1. import javax.servlet.*;2. import javax.servlet.http.*;3. import javax.servlet.jsp.*;4. import javax.servlet.jsp.tagext.*;5. import java.io.PrintWriter;6. import java.io.IOException;7. import java.io.FileInputStream;8. import java.io.ObjectInputStream;9. import java.util.Vector;10. import org.apache.jasper.runtime.*;11. import java.beans.*;12. import org.apache.jasper.JasperException;

Page 29: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(2 of 8)13. public class

_0002fHtml_0002fscriptlet_0002ejspscriptlet_jsp_0 extends HttpJspBase {

14. static { }15. public

_0002fHtml_0002fscriptlet_0002ejspscriptlet_jsp_0( ) { }

16. private static boolean _jspx_inited = false;

17. public final void _jspx_init() throws JasperException { }

Page 30: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(3 of 8)18. public void _jspService(

HttpServletRequest request, HttpServletResponse response)

19. throws IOException, ServletException {20. JspFactory _jspxFactory = null;21. PageContext pageContext = null;22. HttpSession session = null;23. ServletContext application = null;24. ServletConfig config = null;25. JspWriter out = null;26. Object page = this;27. String _value = null;

Page 31: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(4 of 8)28. try {29. if (_jspx_inited == false) {30. _jspx_init();31. _jspx_inited = true;32. }33. _jspxFactory =

JspFactory.getDefaultFactory();34. response.setContentType(35. "text/html;charset=8859_1");36. pageContext =

_jspxFactory.getPageContext( this, request, response, "", true, 8192, true);

Page 32: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(5 of 8)37. application =

pageContext.getServletContext();38. config =

pageContext.getServletConfig();39. session = pageContext.getSession();40. out = pageContext.getOut();41. out.write("<!DOCTYPE HTML PUBLIC \"-

//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<HTML>\r\n <HEAD>\r\n <TITLE>Scriptlet JSP</TITLE>\r\n </HEAD>\r\n <BODY>\r\n\t\t\t<H2>Hello, World!</H2>\t<BR>\r\n\t\t\t<H3>Current Time: ");

Page 33: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(6 of 8)42. out.print( new java.util.Date() );43. out.write("</H3>\r\n\t\t\t"-

<BR>\r\n\t\t\t");44. if (session.getId() != null) { 45. out.write("\r\n\t\t\t\t<H3>"-

Session ID: ");46. out.print( session.getId() );47. out.write("</H3><BR>\r\n\t\t\t");48. } 49. out.write("\r\n\t\t\t<H3>"-

Hostname: ");50. out.print( request.getRemoteHost() );51. out.write("</H3><BR>\r\n\t\t\t");

Page 34: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(7 of 8)52. String testString =

request.getParameter("test");53. if (null == testString) {54. testString = "no.such.parameter";55. }56. out.write("\r\n\t\t\t<H3>"-

Parameter: ");57. out.print( testString );58.

out.write("</H3>\r\n\t</BODY>"-\r\n</HTML>");

Page 35: Object-Oriented Enterprise Application Development JavaServer Pages.

Translated Code – Scriptlet(8 of 8)59. } catch (Exception ex) {60. if (out.getBufferSize() != 0)61. out.clearBuffer();62. pageContext.

handlePageException(ex);63. } finally {64. out.flush();65. _jspxFactory.

releasePageContext(pageContext);66. }67. }68. }

Page 36: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Declarations

A JSP declaration exists outside of the jservice() method.

This means that code in a declaration cannot make use of the implicit variables.

This allows us to declare JSP-level variables and methods.

The tag format of an expression is given by:

<%! java declaration %>

Page 37: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Declaration(1 of 2)1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <HTML>3. <HEAD>4. <TITLE>Declaration JSP</TITLE>5. </HEAD>6. <BODY>7. <H2>Declarations</H2><BR>8. <H3>Current Time:9. <%= new java.util.Date() %>10. </H3><BR>11. <H3>Session ID:12. <%= session.getId() %>13. </H3><BR>

Page 38: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – Declaration(2 of 2)14. <H3>Hostname:15. <%= request.getRemoteHost() %>16. </H3><BR>17. <%! private int accesses = 0; %>18. <H3>19. <%= ++accesses %>20. Accesses to the page since JSP

was loaded.21. </H3>22. </BODY>23. </HTML>

Page 39: Object-Oriented Enterprise Application Development JavaServer Pages.

JSP Directives

Page 40: Object-Oriented Enterprise Application Development JavaServer Pages.

Overview

We use directives to customize the JSP's behavior. Each directive affects the structure of the servlet resulting from the JSP's compilation.

There are three (3) types of directives:page: Controls the servlet's structure.

include: Inserts a file into the servlet class.

taglib: Defines custom markup tags.

Page 41: Object-Oriented Enterprise Application Development JavaServer Pages.

Page Directives

There are many page directives. We'll look at a few of the most common attributes:import

isThreadSafe

session

errorPage

We use the directive tag to indicate that we want a directive to take effect:<%@ directive %>

Page 42: Object-Oriented Enterprise Application Development JavaServer Pages.

Import Attribute

The import attribute allows a JSP to import class libraries:<%@ page import="java.util.*" %>

By default a JSP automatically imports:java.lang.*

java.servlet.*

java.servlet.http.*

java.servlet.jsp.*

Page 43: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - Import1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <%@ page import=“java.util.Date” %>3. <HTML>4. <HEAD>5. <TITLE>Import JSP</TITLE>6. </HEAD>7. <BODY>8. <H2>Imports</H2><BR>9. <H3>Current Time:10. <%= new Date() %>11. </H3>12. </BODY>13. </HTML>

Page 44: Object-Oriented Enterprise Application Development JavaServer Pages.

isThreadSafe Attribute

The isThreadSafe attribute forces the JSP's servlet to implement the SingleThreadedModel interface:<%@ page isThreadSafe="true" %>

By default a JSP is assumed to be thread safe in the same way that servlets are.

If this isn't the case you can:Make it thread-safe using synchronized blocks

Set isThreadSafe to false.

Page 45: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – IsThreadSafe(1 of 2)

1. <%! private int id = 0; %>2. <%3. String userId = "id" + id;4. out.println("Your id is " + id);5. id++;6. %>

Page 46: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – IsThreadSafe(2 of 2)

1. <%! private int id = 0; %>2. <%3. synchronized (this) {4. String userId = "id" + id;5. out.println("Your id is " + id);6. id++;7. }8. %>

Page 47: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - IsThreadSafe1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <%@ page import=“java.util.Date” %>3. <%@ page isThreadSafe=“false” %>4. <HTML>5. <HEAD>6. <TITLE>Single Thread JSP</TITLE>7. </HEAD>8. <BODY>9. <%! private int accesses = 0; %>10. <%= ++accesses %> 11. Accesses since JSP was loaded.12. </BODY>13. </HTML>

Page 48: Object-Oriented Enterprise Application Development JavaServer Pages.

Session Attribute

The session attribute controls whether or not the JSP can access the client's session:<%@ page session="true" %>

By default a JSP participates in the client's session. <%@ page session="true" %>

If this isn't the behavior we want, we can turn it off:<%@ page session="false" %>

Page 49: Object-Oriented Enterprise Application Development JavaServer Pages.

errorPage Attribute

The errorPage attribute specifies the URL to which the client will be sent if an unhandled exception is encountered:<%@ page errorPage="some URL" %>

The exception that caused the problem will be provided to the page via the exception variable.

Page 50: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - ErrorPage1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <%@ page errorPage=“error.jsp” %>3. <HTML>4. <HEAD>5. <TITLE>ErrorPage JSP</TITLE>6. </HEAD>7. <BODY>8. <H3>Session Variable:9. <%=10. session.11. getAttribute("var").toString()12. %>13. </BODY>14. </HTML>

Page 51: Object-Oriented Enterprise Application Development JavaServer Pages.

Integrating Servlets and JavaServer Pages

Page 52: Object-Oriented Enterprise Application Development JavaServer Pages.

Integration

JavaServer Pages allow graphic designers to achieve reasonable separation between their roles and the role of the servlet developer.

However, since all of these components will be used together in the final application, we need to integrate them.

Page 53: Object-Oriented Enterprise Application Development JavaServer Pages.

Request Dispatcher

We've already looked at one approach to integrating servlets and JSPs: the RequestDispatcher class.

This remains the simplest way of invoking a JSP from a servlet.

Page 54: Object-Oriented Enterprise Application Development JavaServer Pages.

Shared Data

It isn't uncommon to need to share data between a servlet and a JSP.

The servlet may perform all of the business processing necessary to generate the data to be displayed by the JSP.

We could use the client's session, but what if the data isn't required beyond a single request-response pair?

Page 55: Object-Oriented Enterprise Application Development JavaServer Pages.

Request Attributes(1 of 2)

For data that needs to exist only for a single client request, we can use the HttpServletRequest object to store our data.

In addition to the parameters passed in by the client, the HttpServletRequest contains attributes which can be set by servlets and JSPs.

Page 56: Object-Oriented Enterprise Application Development JavaServer Pages.

Request Attributes(2 of 2)

As with session attributes, request attributes are nothing more than a name-value pair.

To manipulate these attributes you can use the following methods:public void setAttribute(String, Object)

public Object getAttribute(String)

Page 57: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – SetData(1 of 3)1. import java.io.*;2. import java.util.*;3. import javax.servlet.*;4. import javax.servlet.http.*;

5. public class SendData6. extends HttpServlet {7. public void

doPost(HttpServletRequest rqst, HttpServletResponse resp)

8. throws ServletException, IOException {9. doGet(rqst, resp);10. }

Page 58: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – SetData(2 of 3)11. public void

doGet(HttpServletRequest rqst, HttpServletResponse resp)

12. throws ServletException, IOException {13. rqst.setAttribute("parm", "skippy");14. chain(rqst, resp, "GetData.jsp");15. }

Page 59: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code – SetData(3 of 3)16. private void

chain(HttpServletRequest rqst, HttpServletResponse resp,

String URL)17. throws ServletException, IOException {18. RequestDispatcher dispatcher =

getServletContext(). getRequestDispatcher(URL);

19. dispatcher.forward(rqst, resp);20. }21. }

Page 60: Object-Oriented Enterprise Application Development JavaServer Pages.

Sample Code - GetData1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.0 Transitional//EN">2. <HTML>3. <HEAD>4. <TITLE>GetData JSP</TITLE>5. </HEAD>6. <BODY>7. <H2>Get Shared Value</H2><BR>8. <H3>The shared value is... 9. <%= request.getAttribute("parm") %>10. </H3>11. </BODY>12. </HTML>

Page 61: Object-Oriented Enterprise Application Development JavaServer Pages.

Review

During this class we have discussed:

Anatomy of a JavaServer Page

Merging markup with Java

Configuring our JSPs with directives

Integrating servlets and JSPs

Page 62: Object-Oriented Enterprise Application Development JavaServer Pages.

Resources

Core Servlets and JavaServer PagesMarty Hall, Prentice-Hall, Inc., 2000.ISBN: 0-13-089340-4

Java 2 Platform, Enterprise EditionB. Shannon, et al., Addison-Wesley, 2000.ISBN: 0-201-70456-0

Page 63: Object-Oriented Enterprise Application Development JavaServer Pages.

Coming Attractions

Next week we'll add custom tags to our JavaServer Pages.

Please read Chapter 14 in your text.