jsp – java server pages part 1 representation and management of data on the internet

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

Post on 19-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

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

JSP – Java Server PagesJSP – Java Server PagesPart 1Part 1

Representation and Management of Data on the Internet

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

IntroductionIntroduction

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

What is JSP Good For?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("<h1>Bla Bla</h1>" + "bla bla bla bla"

+ "lots more here...")

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

JSP IdeaJSP 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/

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

RelationshipsRelationships

• Servlets: HTML code is printed in Java code

• JSP: Java code is embedded in HTML code

Java

HTMLJava

HTML

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

ExampleExample

<html>

<head>

<title>Hello World</title>

</head>

<body>

<h2><%= new java.util.Date() %></h2>

<h1>Hello World</h1>

</body>

</html>

Tomcat 5.0 Generated Servlet

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

Generated Servlet HierarchyGenerated Servlet Hierarchy(Tomcat 5.0 Implementation)(Tomcat 5.0 Implementation)

Apache

Implementation

Generated

Servlet

Sun

Specifications

GenericServlet

Servlet

JspPage

HttpJspPageHttpServlet

HttpJspBase

mypage_jsp

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

JSP Limitations and AdvantagesJSP 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

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

JSP Life CycleJSP Life Cycle

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

JSP Life CycleJSP Life Cycle

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

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

JSP Life CycleJSP Life Cycle

Page first w

ritten

Request#1

Request#2

Server restarted

Request#3

Request#4

Page m

odified

Request#5

Request#6

JSP page translated into servlet

Yes No No No Yes No

Servlet compiled Yes No No No Yes No

Servlet instantiated and loaded into server's memory

Yes No Yes No Yes No

init (or equivalent) called

Yes No Yes No Yes No

doGet (or equivalent) called

Yes Yes Yes Yes Yes Yes

Written by Marty Hall. Core Servlets & JSP book: www.coreservlets.com

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

JSP TranslationJSP 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

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

init()init() and and destroy()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

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

Thread SynchronizationThread 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 (_jspService) may be executed by several concurrent threads

• Thus, like Servlets, JSP programming requires concurrency management

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

Basic JSP ElementsBasic JSP Elements

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

Basic Elements in a JSP fileBasic 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...

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

JSP ExpressionsJSP 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()) %>

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

JSP ExpressionsJSP 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...

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

Expression TranslationExpression Translation

<h1>A Random Number</h1><%= Math.random() %>

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws java.io.IOException, ServletException { ... response.setContentType("text/html"); ... out.write("<h1>A Random Number</h1>\r\n"); out.print( Math.random() );

out.write("\r\n"); ...

}

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

Predefined Variables (Implicit Objects)Predefined Variables (Implicit Objects)

• The following predefined variables can be used:

- request: the HttpServletRequest

- response: the HttpServletResponse

- session: the HttpSession associated with the request

- out: the PrintWriter (a buffered version of type JspWriter) used to fill the response content

- application: The ServletContext

• These variables and more will be discussed in details

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

<html>

<head>

<title>JSP Expressions</title>

</head>

<body>

<h2>JSP Expressions</h2>

<ul>

<li>Current time: <%= new java.util.Date() %></li>

<li>Your hostname:<%= request.getRemoteHost() %></li>

<li>Your session ID: <%= session.getId() %></li>

<li>The <code>testParam</code> form parameter:

<%= request.getParameter("testParam") %></li>

</ul>

</body>

</html>

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

JSP ScripletsJSP Scriplets

• JSP scriptlets let you insert arbitrary code into the Servlet service method ( _jspService )

• 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

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

<%= foo() %> <% bar(); %>

public void _jspService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

...response.setContentType("text/html");...out.print(foo());bar();...

}

Scriptlet TranslationScriptlet Translation

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

An Interesting ExampleAn 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!"); }

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

JSP DeclarationsJSP 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 someField = 5; %>

<%! private void someMethod(...) {...} %>

• It is usually of better design to define methods in a separate Java class...

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

Declaration ExampleDeclaration Example

• Print the number of times the current page has been requested since the Servlet initialization:

<%! private int accessCount = 0; %>

<%! private synchronized int incAccess() {

return ++accessCount;

} %>

<h1>Accesses to page since Servlet init:

<%= incAccess() %> </h1>

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

public class serviceCount_jsp extends... implements...

throws... {

private int accessCount = 0;

private synchronized int incAccess() {

return ++accessCount;

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

...

...

out.write("<h1>Accesses to page since Servlet init: ");

out.print(incAccess());

... } ... }

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

jspInit jspInit andand jspDestroy jspDestroy

• 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 jspInit and jspDestroy- The generated servlet is guaranteed to call these methods from

init and destroy, respectively

- The standard versions of jspInit and jspDestroy are empty (placeholders for you to override)

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

JSP DirectivesJSP 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 attribute1="value1" ...

attributeN="valueN" %>

• Three directives: page, include and taglib

• include and taglib will be discussed later

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

pagepage-Directive Attributes-Directive Attributes

• import attribute: A comma separated list of

classes/packages to import

<%@ page import="java.util.*, java.io.*" %>

• contentType attribute: Sets the MIME-Type of the

resulting document (default is text/html)

<%@ page contentType="text/plain" %>

• What is the difference between setting the contentType

attribute, and writing <

%response.setContentType("...");%> ?

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

More More pagepage-Directive Attributes-Directive Attributes

• session="true|false" - use a session?

• buffer="sizekb|none"

- Specifies the content-buffer size (out)

• autoFlush="true|false"

- Specifies whether the buffer should be flushed when

it fills, or throw an exception otherwise

• isELIgnored ="true|false"

- Specifies whether JSP expression language is used

- EL is discussed later

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

Variables in JSP Variables in JSP

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

Implicit ObjectsImplicit 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

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

The objectsThe objects request request and and responseresponse

• request and response are the HttpServletRequest and HttpServletResponse arguments of the service method

• Using these objects, you can:

• Read request parameters

• Set response headers

• etc. (everything we learned in Servlet lectures)

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

The objectThe object out out

• This is the Writer used to add write output into the response body

• This object implements the interface JspWriter that combines the functionality of PrintWriter and BufferedWriter

• Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute of the page directive

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

The objectThe object pageContext pageContext

• pageContext 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)

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

The objectThe object session session

• This is the HttpSession 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

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

The objectThe object config config

• This is the ServletConfig 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 ServletContext from config

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

The objectThe object application application

• This is the ServletContext as obtained via

getServletConfig().getContext()

• Remember:

- The ServletContext is shared by all Web-application

Servlets (including ones generated from JSP)

- Getting and setting attributes is with getAttribute and

setAttribute of ServletContext

- You can use this object to get application-wide

initialization parameters

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

Page ScopePage Scope

• service() local variables

• pageContext attributes

client 1

client 2

a.jsp

b.jsp

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

Request ScopeRequest Scope

• request attributes

client 1

client 2

a.jsp

b.jsp

client 1

client 2

a.jsp

b.jsp

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

Session ScopeSession Scope

• session attributes

client 1

client 2

a.jsp

b.jsp

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

Servlet ScopeServlet Scope

• Servlet members

client 1

client 2

a.jsp

b.jsp

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

Application ScopeApplication Scope

• application attributes

client 1

client 2

a.jsp

b.jsp

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

Servlet Package and Helper ClassesServlet 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

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

JSP and XMLJSP and XML

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

Simple XML ProductionSimple 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 contentType="text/xml" %>

<colors>

<% for(int i=0; i<3; ++i) { %>

<color id="<%=i%>"><%= colors[i] %></color>

<% } %>

</colors>

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

Generated XMLGenerated 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>

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

• 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

JSPX FilesJSPX Files

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

<%= Expression %><jsp:expression> Expression

</jsp:expression>

<% Code %><jsp:scriptlet>

Code

</jsp:scriptlet>

<%! Declaration %><jsp:declaration> Declaration

</jsp:declaration>

<%@ Directive %><jsp:directive.typeAttribute="value"/>

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

Problems with JSPXProblems 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)

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

<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>

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

JSP as JSPXJSP 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

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

<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>

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

Using External ParametersUsing External Parameters

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

JSP Initial ParametersJSP 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>

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

<web-app>

<context-param>

<param-name>dbLogin</param-name>

<param-value>snoopy</param-value>

</context-param>

<context-param>

<param-name>dbPassword</param-name>

<param-value>snoopass</param-value>

</context-param>

An ExampleAn Example

web.xml

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

<servlet>

<servlet-name>ParamPage</servlet-name>

<jsp-file>/paramPage.jsp</jsp-file>

<init-param>

<param-name>tableName</param-name>

<param-value>users</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>ParamPage</servlet-name>

<url-pattern>/paramPage.jsp</url-pattern>

</servlet-mapping>

</web-app>

web.xml

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

<html>

<head><title>JSP initial parameters</title></head>

<body>

<h1>Hello</h1>

<h2>I should use the table

<i><%= config.getInitParameter("tableName") %></i>

</h2>

<h2>To access the Database, I should use the login

<i><%= application.getInitParameter("dbLogin") %></i>

and the password

<i><%= application.getInitParameter("dbPassword") %></i>.

</h2>

</body>

</html>

paramPage.jsp