JSP Java Server Pages Part 1 Representation and

  • Slides: 59
Download presentation
JSP – Java Server Pages Part 1 Representation and Management of Data on the

JSP – Java Server Pages Part 1 Representation and Management of Data on the Internet

Introduction

Introduction

What is JSP Good For? • Servlets allow us to write dynamic Web pages

What is JSP Good For? • 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 not convenient to write and maintain long static HTML using Servlets out. println("<h 1>Bla Bla</h 1>" + "bla bla bla" + "lots more here. . . ")

JSP Idea • Use HTML for most of the page • Write Servlet code

JSP 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 the latter is actually invoked - In Tomcat 5. 0, you can find the generated Servlet code under $CATALINA_BASE/work/

Relationships • Servlets: HTML code is printed in Java code • JSP: Java code

Relationships • Servlets: HTML code is printed in Java code • JSP: Java code is embedded in HTML code Java HTML Java

Example <html> <head> <title>Hello World</title> </head> <body> <h 2><%= new java. util. Date() %></h

Example <html> <head> <title>Hello World</title> </head> <body> <h 2><%= new java. util. Date() %></h 2> <h 1>Hello World</h 1> </body> </html> Tomcat 5. 0 Generated Servlet

Generated Servlet Hierarchy (Tomcat 5. 0 Implementation) Sun Specifications Apache Implementation Generated Servlet

Generated Servlet Hierarchy (Tomcat 5. 0 Implementation) Sun Specifications Apache Implementation Generated Servlet

JSP Limitations and Advantages • JSP can only do what a Servlet can do

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 use a "reverse engineering technique": create static HTML and then replace static data with Java code

JSP Life Cycle

JSP Life Cycle

JSP Life Cycle The following table describes the life cycle of JSP generated Servlet

JSP Life Cycle The following table describes the life cycle of JSP generated Servlet in details:

JSP Life Cycle Request #4 Request #5 Request #6 JSP page translated into servlet

JSP Life Cycle Request #4 Request #5 Request #6 JSP page translated into servlet Yes No No No Yes No Servlet compiled Yes No No No Yes No init (or equivalent) called Yes No do. Get (or equivalent) called Yes Yes Yes Servlet instantiated and loaded into server's memory Page modified Request #3 Server restarted Request #2 Page first written Request #1 Written by Marty Hall. Core Servlets & JSP book: www. coreservlets. com

JSP Translation • When the JSP file is modified, JSP is translated into a

JSP Translation • When the JSP file is modified, JSP is translated into a Servlet - Application need not be reloaded when JSP file is modified • Server does not generate the Servlet class after startup, if the latter already exists - Generated Servlet acts just like any other Servlet

init() and destroy() • init() of the generated Servlet is called every time the

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 • The latter two happen even if the reason is modification of the JSP file

Thread Synchronization • After the Servlet is generated, one instance of it serves requests

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 (_jsp. Service) may be executed by several concurrent threads • Thus, like Servlets, JSP programming requires concurrency management

Basic JSP Elements

Basic JSP Elements

Basic Elements in a JSP file • HTML code: <html-tag>content</html-tag> • JSP Comments: <%--

Basic Elements in a JSP file • HTML code: <html-tag>content</html-tag> • JSP Comments: <%-- comment --%> • Expressions: <%= expression %> • Scriptlets: <% code %> • Declarations: <%! code %> • Directives: <%@ directive attribute="value" %> • Actions: <jsp: forward. . . />, <jsp: include. . . /> • EL Expressions: ${expression} Covered Later. . .

JSP Expressions • A JSP expression is used to insert Java values directly into

JSP Expressions • A JSP expression is used to insert Java values directly into the output • It has the form: <%= expression %> , where expression can be a Java object, a numerical expression, a method call that returns a value, etc. . . • For example: <%= new java. util. Date() %> <%= "Hello"+" World" %> <%= (int)(100*Math. random()) %>

JSP Expressions • A JSP Expression is evaluated • The result is converted to

JSP Expressions • 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. . .

Expression Translation <h 1>A Random Number</h 1> <%= Math. random() %> public void _jsp.

Expression Translation <h 1>A Random Number</h 1> <%= Math. random() %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws java. io. IOException, Servlet. Exception { . . . response. set. Content. Type("text/html"); . . . out. write("<h 1>A Random Number</h 1>rn"); out. print( Math. random() ); out. write("rn"); . . . }

Predefined Variables (Implicit Objects) • The following predefined variables can be used: - request:

Predefined Variables (Implicit Objects) • The following predefined variables can be used: - request: the Http. Servlet. Request - response: the Http. Servlet. Response - session: the Http. Session associated with the request - out: the Print. Writer (a buffered version of type Jsp. Writer) used to fill the response content - application: The Servlet. Context • These variables and more will be discussed in details

<html> <head> <title>JSP Expressions</title> </head> <body> <h 2>JSP Expressions</h 2> <ul> <li>Current time: <%=

<html> <head> <title>JSP Expressions</title> </head> <body> <h 2>JSP Expressions</h 2> <ul> <li>Current time: <%= new java. util. Date() %></li> <li>Your hostname: <%= request. get. Remote. Host() %></li> <li>Your session ID: <%= session. get. Id() %></li> <li>The <code>test. Param</code> form parameter: <%= request. get. Parameter("test. Param") %></li> </ul> </body> </html>

JSP Scriplets • JSP scriptlets let you insert arbitrary code into the Servlet service

JSP Scriplets • JSP scriptlets let you insert arbitrary code into the Servlet service method ( _jsp. Service ) • Scriptlets have the form: <% Java Code %> • The code is inserted verbatim into the service method, according to the location of the scriplet • Scriptlets have access to the same automatically defined variables as expressions

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException {. . . response. set. Content. Type("text/html"); . . . out. print(foo()); bar(); . . . }

An Interesting Example Scriptlets don't have to be complete code blocks: <% if (Math.

An Interesting Example Scriptlets don't have to be complete code blocks: <% if (Math. random() < 0. 5) { %> You <b>won</b> the game! <% } else { %> You <b>lost</b> the game! <% } %> if (Math. random() < 0. 5) { out. write("You <b>won</b> the game!"); } else { out. write("You <b>lost</b> the game!"); }

JSP Declarations • A JSP declaration lets you define methods or members that get

JSP Declarations • A JSP declaration lets you define methods or members that get inserted into the Servlet class (outside of all methods) • It has the following form: <%! Java Code %> • For example: <%! private int some. Field = 5; %> <%! private void some. Method(. . . ) {. . . } %> • It is usually of better design to define methods in a separate Java class. . .

Declaration Example • Print the number of times the current page has been requested

Declaration Example • Print the number of times the current page has been requested since the Servlet initialization: <%! private int access. Count = 0; %> <%! private synchronized int inc. Access() { return ++access. Count; } %> <h 1>Accesses to page since Servlet init: <%= inc. Access() %> </h 1>

public class service. Count_jsp extends. . . implements. . . throws. . . {

public class service. Count_jsp extends. . . implements. . . throws. . . { private int access. Count = 0; private synchronized int inc. Access() { return ++access. Count; } public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException {. . . out. write("<h 1>Accesses to page since Servlet init: "); out. print(inc. Access()); . . . }

jsp. Init and jsp. Destroy • In JSP pages, like regular Servlets, we sometimes

jsp. Init and jsp. Destroy • In JSP pages, like regular Servlets, we sometimes 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 jsp. Init and jsp. Destroy - The generated servlet is guaranteed to call these methods from init and destroy, respectively - The standard versions of jsp. Init and jsp. Destroy are empty (placeholders for you to override)

JSP Directives • A JSP directive affects the structure of the Servlet class that

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: <%@ directive attribute 1="value 1". . . attribute. N="value. N" %> • Three directives: page, include and taglib • include and taglib will be discussed later

page-Directive Attributes • import attribute: A comma separated list of classes/packages to import <%@

page-Directive Attributes • import attribute: A comma separated list of classes/packages to import <%@ page import="java. util. *, java. io. *" %> • content. Type attribute: Sets the MIME-Type of the resulting document (default is text/html) <%@ page content. Type="text/plain" %> • What is the difference between setting the content. Type attribute, and writing <%response. set. Content. Type(". . . "); %> ?

More page-Directive Attributes • session="true|false" - use a session? • buffer="sizekb|none" - Specifies the

More page-Directive Attributes • session="true|false" - use a session? • buffer="sizekb|none" - Specifies the content-buffer size (out) • auto. Flush="true|false" - Specifies whether the buffer should be flushed when it fills, or throw an exception otherwise • is. ELIgnored ="true|false" - Specifies whether JSP expression language is used - EL is discussed later

Variables in JSP

Variables in JSP

Implicit Objects • As seen before, some useful variables, like request and session are

Implicit Objects • As seen before, some useful variables, like request and session are predefined • These variables are called implicit objects • Implicit objects are defined in the scope of the service method - Can these be used in JSP declarations? • Implicit objects are part of the JSP specifications

The objects request and response • request and response are the Http. Servlet. Request

The objects request and response • request and response are the Http. Servlet. Request and Http. Servlet. Response arguments of the service method • Using these objects, you can: • Read request parameters • Set response headers • etc. (everything we learned in Servlet lectures)

The object out • This is the Writer used to add write output into

The object out • This is the Writer used to add write output into the response body • This object implements the interface Jsp. Writer that combines the functionality of Print. Writer and Buffered. Writer • Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute of the page directive

The object page. Context • page. Context is a new object introduced by JSP

The object page. Context • page. Context is a new object introduced by JSP • This object stores all important elements used by the generated Servlet, like the application context, the session, the output writer, etc. • It enable vendors to elegantly extend their JSP implementation • This object is also used to store page-scoped attributes (e. g. , Java Beans - discussed later)

The object session • This is the Http. Session object associated with the request

The object session • This is the Http. Session object associated with the request • If the session attribute in the page directive is turned off (<%@ page session="false" %>) then this object is not available • Recall that a session is created by default

The object config • This is the Servlet. Config of the page, as received

The object config • This is the Servlet. Config of the page, as received in the init() method • Remember: contains Servlet specific initialization parameters • Later, we will study how initialization parameters are passed to JSP pages • Recall that you can also obtain the Servlet. Context from config

The object application • This is the Servlet. Context as obtained via get. Servlet.

The object application • This is the Servlet. Context as obtained via get. Servlet. Config(). get. Context() • Remember: - The Servlet. Context is shared by all Web-application Servlets (including ones generated from JSP) - Getting and setting attributes is with get. Attribute and set. Attribute of Servlet. Context - You can use this object to get application-wide initialization parameters

Page Scope • service() local variables • page. Context attributes

Page Scope • service() local variables • page. Context attributes

Request Scope • request attributes

Request Scope • request attributes

Session Scope • session attributes

Session Scope • session attributes

Servlet Scope • Servlet members

Servlet Scope • Servlet members

Application Scope • application attributes

Application Scope • application attributes

Servlet Package and Helper Classes • The generated Servlet has a named package •

Servlet Package and Helper Classes • The generated Servlet has a named package • In Tomcat, this package is: org. apache. jsp • In Java, you cannot use classes from the default package (i. e. with no package declaration) from a named package! • Therefore, helper classes used by JSP pages must have a named package

JSP and XML

JSP and XML

Simple XML Production <? xml version="1. 0"? > <!DOCTYPE colors SYSTEM "colors. dtd"> <?

Simple XML Production <? xml version="1. 0"? > <!DOCTYPE colors SYSTEM "colors. dtd"> <? xml-stylesheet type="text/xsl" href="colors. xsl"? > <%! static String[] colors = {"red", "blue", "green"}; %> <%@ page content. Type="text/xml" %> <colors> <% for(int i=0; i<3; ++i) { %> <color id="<%=i%>"><%= colors[i] %></color> <% } %> </colors>

Generated XML <? xml version="1. 0"? > <!DOCTYPE colors SYSTEM "colors. dtd"> <? xml-stylesheet

Generated XML <? xml version="1. 0"? > <!DOCTYPE colors SYSTEM "colors. dtd"> <? xml-stylesheet type="text/xsl" href="colors. xsl"? > <colors> <color id="0">red</color> <color id="1">blue</color> <color id="2">green</color> </colors>

JSPX Files • JSPX files are JSP files that have the extension jspx and

JSPX Files • JSPX files are JSP files that have the extension jspx and have XML syntax • Non-XML symbols <%, <%@, etc. are replaced with special JSP tags • Default content type of JSPX is text/xml (and not text/html) • Thus, JSPX files generate XML and can be edited using XML tools

<%= Expression %> <jsp: expression> Expression </jsp: expression> <% Code %> <jsp: scriptlet> Code

<%= Expression %> <jsp: expression> Expression </jsp: expression> <% Code %> <jsp: scriptlet> Code </jsp: scriptlet> <%! Declaration %> <jsp: declaration> Declaration </jsp: declaration> <%@ Directive %> <jsp: directive. type Attribute="value"/>

Problems with JSPX • The XML declaration (<? xml version="1. 0"? >) and the

Problems with JSPX • The XML declaration (<? xml version="1. 0"? >) and the DOCTYPE definition are now those of the JSPX file. How do we include those in the result XML? - Solution: use the <jsp: output> tag to explicitly require DOCTYPE and XML declarations • How do we generate dynamic attribute values and still keep the document well formed? - Solution 1: use <jsp: element> for explicit element construction - Solution 2: use an EL expression (discussed later)

<colors xmlns: jsp="http: //java. sun. com/JSP/Page"> <jsp: output doctype-root-element="colors" doctype-system="colors. dtd" /> <jsp: output

<colors xmlns: jsp="http: //java. sun. com/JSP/Page"> <jsp: output doctype-root-element="colors" doctype-system="colors. dtd" /> <jsp: output omit-xml-declaration="false"/> <jsp: declaration>static String[] colors = {"red", "blue", "green"}; </jsp: declaration> <jsp: scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp: scriptlet> <jsp: element name="color"> <jsp: attribute name="id"> <jsp: expression>i</jsp: expression> </jsp: attribute> <jsp: expression>colors[i]</jsp: expression> </jsp: element> <jsp: scriptlet>}</jsp: scriptlet> </colors>

JSP as JSPX • You can tell the container that a JSP file acts

JSP as JSPX • You can tell the container that a JSP file acts as a JSPX file • Use the <jsp: root> element as the document root

<jsp: root version="2. 0" xmlns: jsp="http: //java. sun. com/JSP/Page"> <jsp: output doctype-root-element="colors" doctype-system="colors. dtd"

<jsp: root version="2. 0" xmlns: jsp="http: //java. sun. com/JSP/Page"> <jsp: output doctype-root-element="colors" doctype-system="colors. dtd" /> <jsp: output omit-xml-declaration="false"/> <![CDATA[<? xml-stylesheet type="text/xsl" href="colors. xsl"? >]]> <colors > <jsp: declaration>static String[] colors = {"red", "blue", "green"}; </jsp: declaration> <jsp: scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp: scriptlet> <jsp: element name="color"> <jsp: attribute name="id"> <jsp: expression>i</jsp: expression></jsp: attribute> <jsp: expression>colors[i]</jsp: expression> </jsp: element> <jsp: scriptlet>}</jsp: scriptlet> </colors> </jsp: root>

Using External Parameters

Using External Parameters

JSP Initial Parameters • Like Servlets, initialization parameters can be passed to JSP files

JSP Initial Parameters • Like Servlets, initialization parameters can be passed to JSP files using the <servlet> element of the application configuration file web. xml • Use the sub-element <jsp-file> instead of the sub -element <servlet-class> • A <servlet-mapping> is also needed - Use the real JSP URL as the <url-pattern>

An Example web. xml <web-app> <context-param> <param-name>db. Login</param-name> <param-value>snoopy</param-value> </context-param> <param-name>db. Password</param-name> <param-value>snoopass</param-value> </context-param>

An Example web. xml <web-app> <context-param> <param-name>db. Login</param-name> <param-value>snoopy</param-value> </context-param> <param-name>db. Password</param-name> <param-value>snoopass</param-value> </context-param>

web. xml <servlet> <servlet-name>Param. Page</servlet-name> <jsp-file>/param. Page. jsp</jsp-file> <init-param> <param-name>table. Name</param-name> <param-value>users</param-value> </init-param> </servlet>

web. xml <servlet> <servlet-name>Param. Page</servlet-name> <jsp-file>/param. Page. jsp</jsp-file> <init-param> <param-name>table. Name</param-name> <param-value>users</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Param. Page</servlet-name> <url-pattern>/param. Page. jsp</url-pattern> </servlet-mapping> </web-app>

param. Page. jsp <html> <head><title>JSP initial parameters</title></head> <body> <h 1>Hello</h 1> <h 2>I should

param. Page. jsp <html> <head><title>JSP initial parameters</title></head> <body> <h 1>Hello</h 1> <h 2>I should use the table <i><%= config. get. Init. Parameter("table. Name") %></i> </h 2> <h 2>To access the Database, I should use the login <i><%= application. get. Init. Parameter("db. Login") %></i> and the password <i><%= application. get. Init. Parameter("db. Password") %></i>. </h 2> </body> </html>