JSP page translation and processing phases Translation phase
















































- Slides: 48

JSP page translation and processing phases Translation phase Hello. jsp Read Request hello. Servlet. java Generate Client Response Server Execute hello. Servlet. class Processing phase 1

Template Pages Server Page Template Resulting HTML <html> <title> A simple example </title> translation <body color=“#FFFFFF”> The time now is <%= new java. util. Date() %> Tue Nov 5 16: 15: 11 PST 2002 </body> </html> 2 </html>

Dividing Pure Servlets Public class My. Select { public void do. Get(…){ controller Process request if (is. Valid(. . ){ save. Record(); out. println(“<html>”); Presentation } private void is. Valid(…){…} view JSP …. } Servlet model Business logic Java. Beans private void save. Record(…) {…} Model-View-Controller (MVC) design } 3

JSP Components n There are three main types of JSP constructs that you embed in a page. – Scripting elements n n You can specify Java code Expressions, Scriptlets, Declarations – Directives n n Let you control the overall structure of the servlet Page, include, Tag library – Actions n n Enable the use of server side Javabeans Transfer control between pages 4

Types of Scripting Elements n n You can insert code into the servlet that will be generated from the JSP page. Expressions: <%= expression %> – Evaluated and inserted into the servlet’s output. i. e. , results in something like out. println(expression) n Scriptlets: <% code %> – Inserted verbatim into the servlet’s _jsp. Service method (called by service) n Declarations: <%! code %> – Inserted verbatim into the body of the servlet class, outside of any existing methods 5

JSP Expressions n Format – <%= Java Expression %> n Result – Expression evaluated, converted to String, and placed into HTML page at the place it occurred in JSP page – That is, expression placed in _jsp. Service inside out. print n Examples – Current time: <%= new java. util. Date() %> – Your hostname: <%= request. get. Remote. Host() %> n XML-compatible syntax – <jsp: expression>Java Expression</jsp: expression> – XML version not supported by Tomcat 3. Until JSP 1. 2, servers are not required to support it. 6

JSP/Servlet Correspondence n Original JSP <H 1>A Random Number</H 1> <%= Math. random() %> Possible resulting servlet code public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println("<H 1>A Random Number</H 1>"); out. println(Math. random()); . . . } n 7

Example Using JSP Expressions <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new java. util. Date() %> <LI>Your hostname: <%= request. get. Remote. Host() %> <LI>Your session ID: <%= session. get. Id() %> <LI>The <CODE>test. Param</CODE> form parameter: <%= request. get. Parameter("test. Param") %> </UL> </BODY> 8

Predefined Variables (Implicit Objects) n n They are created automatically when a web server processes a JSP page. request: The Http. Servlet. Request (1 st arg to do. Get) response: The Http. Servlet. Response (2 nd arg to do. Get) session – The Http. Session associated with the request (unless disabled with the session attribute of the page directive) n out – The stream (of type Jsp. Writer) used to send output to the client n application – The Servlet. Context (for sharing data) as obtained via get. Servlet. Config(). get. Context(). n page, page. Context, config, exception 9

Implicit objects – Class files n n n n n application: javax. servlet. Servlet. Context config: javax. servlet. Servlet. Config exception: java. lang. Throwable out: javax. servlet. jsp. Jsp. Writer page: java. lang. Object page. Context: javax. servlet. jsp. Page. Context request: javax. servlet. Servlet. Request response: javax. servlet. Servlet. Response session: javax. servlet. http. Http. Session 10

Access Client Information n The get. Remote. Host method of the request object allows a JSP to retrieve the name of a client computer. <html><head> <title>Your Information</title> </head><body> Your computer's IP address is <b><%= request. get. Remote. Addr() %></b> Your computer's name is <b><%= request. get. Remote. Host() %></b> Your computer is accessing port number <b><%= request. get. Server. Port() %></b> </body></html> 11

Work with the Buffer n When the page is being processed, the data is stored in the buffer instead of being directly sent to the client browser. <html> This is a test of the buffer<br/> <% out. flush(); for (int x=0; x < 10000; x++); out. print("This test is generated about 5 seconds later. "); out. flush(); %> </html> 12

Working with Session object n The session object has many useful methods that can alter or obtain information about the current session. – set. Max. Inactive. Interval(second) <html><head> <title>Session Values</title> </head><body> <% session. set. Max. Inactive. Interval(10); String name = (String) session. get. Attribute("username"); out. print("Welcome to my site " + name + " "); %> </body></html> 13

JSP Scriptlets n n Format: <% Java Code %> Result – Code is inserted verbatim into servlet's _jsp. Service n Example – <% String query. Data = request. get. Query. String(); out. println("Attached GET data: " + query. Data); %> – <% response. set. Content. Type("text/plain"); %> n XML-compatible syntax – <jsp: scriptlet>Java Code</jsp: scriptlet> 14

JSP/Servlet Correspondence n Original JSP <%= foo() <% bar(); n %> %> Possible resulting servlet code public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println(foo()); bar(); . . . } 15

JSP Scriptlets Example <% for (int i=100; i>=0; i--) { %> <%= i %> bottles of beer on the wall. <% } %> 16

Example Using JSP Scriptlets <HTML> <HEAD> <TITLE>Color Testing</TITLE> </HEAD> <% String bg. Color = request. get. Parameter("bg. Color"); boolean has. Explicit. Color; if (bg. Color != null) { has. Explicit. Color = true; } else { has. Explicit. Color = false; bg. Color = "WHITE"; } %> <BODY BGCOLOR="<%= bg. Color %>"> 17

JSP Declarations n Format – <%! Java Code %> n Result – Code is inserted verbatim into servlet's class definition, outside of any existing methods n Examples – <%! private int some. Field = 5; %> – <%! private void some. Method(. . . ) {. . . } %> n XML-compatible syntax – <jsp: declaration>Java Code</jsp: declaration> 18

n Original JSP n Possible resulting servlet code <H 1>Some Heading</H 1> <%! private String random. Heading() { return("<H 2>" + Math. random() + "</H 2>"); } %> <%= random. Heading() %> public class xxxx implements Http. Jsp. Page { private String random. Heading() { return("<H 2>" + Math. random() + "</H 2>"); } public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println("<H 1>Some Heading</H 1>"); out. println(random. Heading()); . . . } JSP/Servlet Correspondence 19

Example Using JSP Declarations … <body> <h 1>JSP Declarations</h 1> <%! private int access. Count = 0; %> <h 2>Accesses to page since server reboot: <%= ++access. Count %></h 2> </body></html> n. After 15 total visits by an arbitrary number of different clients 20

JSP Tags + HTML Tags <h 2>Table of Square Roots</h 2> <table border=2> <tr> <td><b>Number</b></td> <td><b>Square Root</b></td> </tr> <% for (int n=0; n<=100; n++) { %> <tr> <td><%=n%></td> <td><%=Math. sqrt(n)%></td> </tr> <% } %> </table> 21

JSP Directives Affect the overall structure of the servlet n Two possible forms for directives n – <%@ directive attribute=“value” %> – <%@ directive attribute 1=“value 1” attribute 2=“value 2” …. attribute. N=“value. N” %> n There are three types of directives – Page, include, and taglib 22

Purpose of the page Directive n n Give high-level information about the servlet that will result from the JSP page Can control – – – – Which classes are imported What class the servlet extends What MIME type is generated How multithreading is handled If the servlet participates in sessions The size and behavior of the output buffer What page handles unexpected errors 23

The import Attribute n Format – <%@ page import="package. class" %> – <%@ page import="package. class 1, . . . , package. class. N" %> n Purpose – Generate import statements at top of servlet n Notes – Although JSP pages can be almost anywhere on server, classes used by JSP pages must be in normal servlet dirs 24

Example of import Attribute . . . <BODY><H 2>The import Attribute</H 2> <%-- JSP page directive --%> <%@ page import="java. util. *, cwp. *" %> <%-- JSP Declaration --%> <%! private String random. ID() { int num = (int)(Math. random()*10000000. 0); return("id" + num); } private final String NO_VALUE = "<I>No Value</I>"; %> <% Cookie[] cookies = request. get. Cookies(); String old. ID = Servlet. Utilities. get. Cookie. Value(cookies, "user. ID", NO_VALUE); String new. ID; if (old. ID. equals(NO_VALUE)) { new. ID = random. ID(); } else { new. ID = old. ID; } Long. Lived. Cookie cookie = new Long. Lived. Cookie("user. ID", new. ID); response. add. Cookie(cookie); %> <%-- JSP Expressions --%> This page was accessed at <%= new Date() %> with a user. ID cookie of <%= old. ID %>. </BODY></HTML> 25

Example of import Attribute n First access n Subsequent accesses 26

The content. Type Attribute n Format – <%@ page content. Type="MIME-Type" %> – <%@ page content. Type="MIME-Type; charset=Character-Set"%> n Purpose – Specify the MIME type of the page generated by the servlet that results from the JSP page 27

First Last Email Address Marty Hall hall@corewebprogramming. com Larry Brown brown@corewebprogramming. com Bill Gates gates@sun. com Larry Ellison ellison@microsoft. com <%@ page content. Type="application/vnd. ms-excel" %> <%-- There are tabs, not spaces, between columns. --%> Generating Excel Spreadsheets 28

<%-- process. Order. jsp --%> <%@ page error. Page="order. Error. jsp" import="java. text. Number. Format" %> <h 3>Your order: </h 3> <% String num. Tees = request. get. Parameter("t-shirts"); String num. Hats = request. get. Parameter("hats"); Number. Format currency = Number. Format. get. Currency. Instance(); %> Number of tees: <%= num. Tees %> Your price: <%= currency. format(Integer. parse. Int(num. Tees)*15. 00) %><p> Number of hats: <%= num. Hats %> Your price: <%= currency. format(Integer. parse. Int(num. Hats)*10. 00) %><p> <!-- order. Form. htm --> <h 1>Order Form</h 1> What would you like to purchase? <p> <form name=orders action=process. Order. jsp> <table border=0> <tr><th>Item</th> <th>Quantity</th> <th>Unit Price</th> <tr> … 29 Form Processing

JSP Actions n There are seven standard JSP actions. – Include, param, forward, plugin, … – Include action is similar to include directive. – You can additional parameters to the existing request by using the param action. – The plugin action inserts object and embed tags (such as an applet) into the response to the client. – In the coming slides, we will talk about “include” and “plugin” actions. 30

Including Pages at Request Time n Format – <jsp: include page="Relative URL" flush="true" /> n Purpose – To reuse JSP, HTML, or plain text content – JSP content cannot affect main page: only output of included JSP page is used – To permit updates to the included content without changing the main JSP page(s) 31

Including Pages: Example Code. . . <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> What's New at Jsp. News. com</TABLE> <P> Here is a summary of our three most recent news stories: <OL> <LI><jsp: include page="news/Item 1. html" flush="true" /> <LI><jsp: include page="news/Item 2. html" flush="true" /> <LI><jsp: include page="news/Item 3. html" flush="true" /> </OL> </BODY></HTML> 32

Background: What Are Beans? n Classes that follow certain conventions – – – Must have a zero-argument (empty) constructor Should have no public instance variables (fields) Persistent values should be accessed through methods called get. Xxx and set. Xxx n n n If class has method get. Title that returns a String, class is said to have a String property named title Boolean properties use is. Xxx instead of get. Xxx For more on beans, see http: //java. sun. com/beans/docs/ 33

Basic Bean Use in JSP n n n Format: <jsp: use. Bean id="name" class="package. Class" /> Purpose: Allow instantiation of classes without explicit Java syntax Notes – Simple interpretation: JSP action <jsp: use. Bean id="book 1" class="cwp. Book" /> can be thought of as equivalent to the scriptlet <% cwp. Book book 1 = new cwp. Book(); %> – But use. Bean has two additional features n n Simplifies setting fields based on incoming request params Makes it easier to share beans 34

Accessing Bean Properties Format: <jsp: get. Property name="name" property="property" /> n Purpose: Allow access to bean properties (i. e. , calls to get. Xxx methods) without explicit Java code n Notes n – <jsp: get. Property name="book 1" property="title" /> is equivalent to the following JSP expression <%= book 1. get. Title() %> 35

Setting Bean Properties: Simple Case Format: <jsp: set. Property name="name" property="property" value="value" /> n Purpose n – Allow setting of bean properties (i. e. , calls to set. Xxx) without explicit Java code n Notes – <jsp: set. Property name="book 1" property="title" value="Core Servlets and JSP" /> is equivalent to the following scriptlet <% book 1. set. Title("Core Servlets and JSP"); %> 36

Example: String. Bean public class String. Bean { private String message = "No message specified"; public String get. Message() { return(message); } public void set. Message(String message) { this. message = message; } } n Installed in normal servlet directory 37

<jsp: use. Bean id="string. Bean" class="cwp. String. Bean" /> <OL> <LI>Initial value (get. Property): <I><jsp: get. Property name="string. Bean" property="message" /> </I> <LI>Initial value (JSP expression): <I><%= string. Bean. get. Message() %></I> <LI><jsp: set. Property name="string. Bean" property="message" value="Best string bean: Fortex" /> Value after setting property with set. Property: <I><jsp: get. Property name="string. Bean" property="message" /> </I> <LI> <% string. Bean. set. Message("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: <I><%= string. Bean. get. Message() %></I> </OL> JSP Page That Uses String. Bean 38

JSP Page That Uses String. Bean 39

Associating Bean Properties with Request (Form) Parameters n If property is a String, you can do – <jsp: set. Property. . . value='<%= request. get. Parameter(". . . ") %>' /> n n Scripting expressions let you convert types, but you have to use Java syntax The param attribute indicates that: – Value should come from specified request param – Simple automatic type conversion performed n Using "*" for the property attribute indicates that: – Value should come from request parameter whose name matches property name – Simple type conversion should be performed 40

Setting Bean Properties Case 1: Explicit Conversion & Assignment <!DOCTYPE. . . >. . . <jsp: use. Bean id="entry" class="cwp. Sale. Entry" /> <%-- get. Item. ID expects a String --%> <jsp: set. Property name="entry" property="item. ID" value='<%= request. get. Parameter("item. ID") %>' /> 41

Setting Bean Properties Case 1: Explicit Conversion & Assignment <% int num. Items. Ordered = 1; try { num. Items. Ordered = Integer. parse. Int(request. get. Parameter("num. Items")); } catch(Number. Format. Exception nfe) {} %> <%-- get. Num. Items expects an int --%> <jsp: set. Property name="entry" property="num. Items" value="<%= num. Items. Ordered %>" /> 42

Setting Bean Properties Case 1: Explicit Conversion & Assignment <% double discount. Code = 1. 0; try { String discount. String = request. get. Parameter("discount. Code"); discount. Code = Double. value. Of(discount. String). double. Value(); } catch(Number. Format. Exception nfe) {} %> <%-- get. Discount. Code expects a double --%> <jsp: set. Property name="entry" property="discount. Code" value="<%= discount. Code %>" /> 43

Case 2: Associating Individual Properties with Input Parameters <jsp: use. Bean id="entry" class="cwp. Sale. Entry" /> <jsp: set. Property name="entry" property="item. ID" param="item. ID" /> <jsp: set. Property name="entry" property="num. Items" param="num. Items" /> <jsp: set. Property name="entry" property="discount. Code" param="discount. Code" /> 44

Case 3: Associating All Properties with Input Parameters <jsp: use. Bean id="entry" class="cwp. Sale. Entry" /> <jsp: set. Property name="entry" property="*" /> 45

Sharing Beans n You can use scope attribute to specify where bean is stored – – n n <jsp: use. Bean id="…" class="…" scope="…" /> Bean still also bound to local variable in _jsp. Service Lets multiple servlets or JSP pages share data Also permits conditional bean creation – Create new object only if you can't find existing one 46

Values of the scope Attribute n page – Default value. Bean object should be placed in the Page. Context object for the duration of the current request. Lets methods in same servlet access bean n application – Bean will be stored in Servlet. Context (available through the application variable or by call to get. Servlet. Context()). Servlet. Context is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). 47

Values of the scope Attribute n session – Bean will be stored in the Http. Session object associated with the current request, where it can be accessed from regular servlet code with get. Attribute and set. Attribute, as with normal session objects. n request – Bean object should be placed in the Servlet. Request object for the duration of the current request, where it is available by means of get. Attribute 48