• No results found

JSP Java Server Pages

N/A
N/A
Protected

Academic year: 2021

Share "JSP Java Server Pages"

Copied!
62
0
0

Loading.... (view fulltext now)

Full text

(1)

JSP - Java Server Pages

JSP

(2)

Characteristics:

A way to create dynamic web pages,

Server side processing,

Based on Java Technology,

Large library base

Platform independence

Separates the graphical design from the

dynamic content.

Ref.:

(3)

Basic idea:

Separating Graphical Design and Dynamic Content

Similar approaches:

PHP, SSI, ASP

Graphical Design and System Design are two

separate and distinct specialities:

Different languages (HTML/XHTML vs. Java),

Different goals, and

Different Training.

Should be separated for optimal project

management.

(4)

<html>

<body>

<b>Hello World HTML!</b><br><br>

<% out.println("Hello World Java"); %>

</body>

</html>

http://149.222.51.81:8180/home-tomcat/jsp/dispert/hello.jsp

(5)

<html>

<body>

<b>Hello World HTML!</b><br><br>

<% out.println("Hello World Java") %>

</body>

</html>

http://http://149.222.51.81:8180/home-tomcat/jsp/dispert/helloError.jsp Missing ";"

(6)
(7)

JSP technology is essentially a language

specification

Used to mix code into text content

Typically HTML or XML

Special syntax embedded into pages

compile Directive blocks

code block

Code snippets that generate into strings

Compile into a servlet

(8)

Java Code

out.println("HTML")

HTML

HTML

Servlet

HTML Page

<% Java %>

Java

Java

JSP

(9)

JSP Compiler

Servlet

Source

Class

File

Java Compiler

JSP

(10)

Browser

Browser

Browser

Browser

App

JSP/Servlet

JSP/Servlet

JDBC

JDBC

EJB

EJB

XML + HTML X,D-HTML XML

XSL/XTL

XSL/XTL

Servlets / Java Server Pages

(11)

Client Response

Request JSP Engine and

Web Server

(Creates a Servlet from a

JSP file and executes the servlet) (HTTP get or post) (HTML File) Response Request Servlet File Response Request Java Component

JSP Engine

(12)

User request a JSP Execute Servlet Page unchanged ? Page compiled before? Compile JSP into Servlet Yes Yes No No

JSP Engine

(13)

• JSP Elements must first be processed by the

server

• JSP Page => Servlet

• Compile Servlet

• Execute Servlet

• Web server must have JSP Container

(14)

Server

(JSP)

(1) GET / Hello.jsp

Hello.jsp

HelloServlet.java

HelloServlet.class

(2) READ (3) GENERATE (4) COMPILE (5) EXECUTE (6) HTTP/1.0 200 OK <html> ... </html>

CLIENT

JSP Translation/Processing

(15)

Javascript

Client side

Less secure

Browser dependent

Unstable

JSP versus Javascript

(16)

Active Server Pages (ASP, Microsoft)

Many similarities

Server side dynamic web page generator

Separate programming logic from page design

Similar syntax <% %>

Proprietary Product

Limited platform

(17)

Disadvantages of Servlets

Processing code & HTML code in same module

Changing look and feel requires servlet

re-compilation

Difficult to leverage web development tools

Generated HTML embedded into Servlet

(18)

Similarities between JSP and Servlets

Identical results to the end user

JSP is an additional module to the Servlet Engine

Differences

Servlets

“HTML in Java code”:

HTML code inaccessible to Graphics Designer,

Everything is accessible to Programmer

JSP

“Java Code Scriptlets in HTML”:

HTML code very accessible to Graphics Designer,

Java code very accessible to Programmer

(19)

JSP is a simple text file consisting of HTML or

XML content along with JSP elements

JSP packages define the interface for the

compiled JSP page

JSPPage

HttpJspPage

Three main methods

jspInit()

jspDestroy()

jspService(HttpServletRequest request,

HttpServletResponse response)

(20)

JSP Elements

“Template Text” - HTML

When request is processed

template text & dynamic content merged

result sent as response to browser

JSP Elements

Directive

Action

Scripting

(21)

Directives

provide global information to the page

Action

perform action based on up-to-date information

Scripting

Declarative:

for page-wide variable and method declaration

Scriptlets:

the Java code embedded in the page

Expressions:

Format the expression as a string for inclusion

(22)

Comment can be viewed in the HTML source file

<!-- comment <% expression%> -->

Example:

<!-- this is just Html comment -->

<!-- This page was loaded on <%= (new java.util.Date

()).toLocaleString()%> -->

View source:

<!-- this is just Html comment -->

<!-- This page was loaded on January 10, 2006 -->

(23)

Comment cannot be viewed in the HTML source

file

<% -- expression -- %>

Example:

<html>

<body>

<h2>A Test of Comments</h2>

<%--This comment will be invisible in page source --%>

</body>

</html>

(24)

A JSP directive is a statement that gives the

JSP engine information for the page.

Syntax:

- <%@ directive {attribute= “value” } %>

For example

- scripting language used

- session tracking required

- name of page for error reporting

(25)

<%@ page ... %>

Define page-dependent attributes, such as

scripting language, error page & buffering

requirements.

<%@ include ... %>

Include a file during the translation phase.

<%@ taglib ... %>

Declares a tag library, containing custom

actions (markup tags), used in the page.

(26)

Includes a static file

<%@ include file="relativeURL" %>

Example:

JSP-File "main.jsp":

<html><body>

Current date and time is:

<%@include file="date.jsp" %> </body></html>

File to include "date.jsp":

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

<% =(new java.util.Date()).toLocaleString() %>

JSP Syntax: Include Directive

(27)

Values

Attribute

true / false

isThreadSafe

text

info

pathToErrorPage

errorPage

true / false

autoflush

none / 8kb / sizekb

buffer

true / false

session

package.* / package.class

import

package.class

extends

java

language

(28)

The definition of class-level variables and

methods

Syntax:

<%! Declaration %>

<%! String var1 = "hi";

int count = 0;

private void incrementCount() {

count++;

}

(29)

Scriptlets definition:

any block of valid Java code that resides between

<% and %> tags.

This code will be placed into the generated

servlet_jspService()

method.

<%

String var1 = request.getParameter("lname");

out.println(var1);

%>

(30)

JSP expression:

used to embed values directly within HTML code.

Syntax:

<%= expression %>

Example:

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

<BR>

Counter value is

<%= i %>

<% } %>

(31)

<HTML>

<HEAD><TITLE>JSP Expressions</TITLE></HEAD> <BODY>

<H2>JSP Expressions</H2> <UL>

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

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

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

<LI>The <CODE>testParam</CODE> form parameter:

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

</UL> </BODY> </HTML>

(32)
(33)

<HTML>

<HEAD><TITLE>JSP Expressions</TITLE></HEAD> <BODY>

<H2>JSP Expressions</H2> <UL>

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

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

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

<LI>The <CODE>testParam</CODE> form parameter:

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

</UL> </BODY> </HTML>

(34)
(35)

Implicit JSP Objects

Scripting

.ServletConfig

config

.jsp.JspWriter

out

.ServletContext

application

.http.Session

session

.jsp.PageContext

pageContext

.http.HttpServletResponse

response

.http.HttpServletRequest

request

(36)

<%@ page errorPage="errorpage.jsp" %>

<html> <head>

<title>UseSession</title>

</head>

<body>

<%

// Try and get the current count from the session

Integer count =

(Integer)session.getAttribute("COUNT");

// If COUNT is not found, create it and add it to

Session Example

(37)

if ( count == null ) {

count = new Integer(1);

session.setAttribute("COUNT", count);

}

else {

count = new Integer(count.intValue() + 1);

session.setAttribute("COUNT", count);

}

// Get the User's Name from the request

out.println("<b>Hello you have visited this site:

"

+ count + " times.</b>");

%>

</body> </html>

Session Example

(38)

XML

(39)

XML Syntax for Expressions:

<jsp: expression>

Java Expression

</jsp: expression>

XML Syntax for Scriptlets:

<jsp: scriptlet>

Code

</jsp: scriptlet>

(40)

XML Syntax for Declarations:

<jsp: declaration>

Code

</jsp: declaration>

XML Syntax for Directives:

<jsp: directive.directiveType attribute="value" /> example:

<jsp: directive.page import="java.util.*" /> equivalent of:

(41)

Applications

(42)

<%@ page contentType="application/vnd.ms-excel" %> <%-- tabs between columns! --%>

2003 2004 2005 2006 2007

10 20 30 40 50

Tab

(43)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Student Numbers</TITLE> </HEAD> <BODY> <H3>Student Numbers</H3> <%

String format = request.getParameter("format");

if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); }

(44)

<TABLE BORDER=1> <TR><TH></TH><TH>SS2007<TH>WS2007/08 <TR><TH>Mult<TD>108<TD>108 <TR><TH>L<TD>272<TD>272 <TR><TH>IuE<TD>668<TD>668 <TR><TH>M<TD>745<TD>745 <TR><TH>B<TD>935<TD>935 <TR><TH>SAG<TD>953<TD>953 <TR><TH>W<TD>1401<TD>1401 </TABLE> </CENTER> </BODY> </HTML>

HTML table

interpreted by Excel

(45)

HTML Page

Generating Excel Sheets

(46)

Excel Sheet

Generating Excel Sheets

(47)

JSP - Java Server Pages

(48)

Unique feature of JSP:

Tag Libraries - Taglibs

custom defined JSP tags.

used to componentize presentation level logic.

similar to Java beans.

Basic idea:

Every tag is mapped to a particular class file which is executed

whenever the tag is encountered in a JSP file.

General syntax :

<%@ taglib uri = " --- " prefix = " --- " %>

JSP-tags can be nested within other tags.

(49)

Steps to create and use TAGLIBs :

1.

create the class file which should implement the

Tag

and

BodyTag

interfaces

2.

deploy the class file in the Servlet folder of the web server.

3.

mapping of a tag to a particular class is done through the

use of the file "

taglib.tld

".

The taglib file represents an XML document that defines

the tag operation.

4.

Tag library is made available to the JSP page using the

taglib

directive.

(50)

Tag Handler

The Tag Handler is responsible for the interaction between

the JSP page and additional server-side objects. The handler

is invoked during the execution of a JSP page when a

custom tag is encountered.

Two interfaces describe a tag handler:

an extension of

Tag

and gives the handler

access to its body

BodyTag

used for simple tag handlers not interested

in manipulating their body content

Tag

(51)

The Tag Handler has two main action methods:

Process the end tag of this action.

Called after returning from doStartTag.

doEndTag()

Release resources

release()

Process the start tag of this action.

doStartTag()

(52)

Tag interaction.

Tag

1: setPageContext (javax.servlet.jsp.PageContext):void

Container

2: setParent (javax.servlet.jsp.tagext.Tag):void 3: //setAttribute:void 4: doStartTag()):int 5: doEndTag()):int 6: release()):int

(53)

Tag interaction.

Container function after page is parsed and a tag is encountered:

1. Use the setPageContext() method of the Tag to set the current PageContext for it to use.

2. Use the setParent() method to set any parent of the encountered Tag (or null if none).

3. Set any attributes defined to be given to the Tag.

4. Call the doStartTag() method. This method can either return

EVAL_BODY_INCLUDE or SKIP_BODY. If EVAL_BODY_INCLUDE is returned, the Tags body will be evaluated. If SKIP_BODY is returned, the Container will not evaluate the body of the Tag.

5. Call the doEndTag() method. This method can either return EVAL_PAGE or SKIP_PAGE. IF EVAL_PAGE is returned, the Container will continue to evaluate the JSP page when done with this Tag. If SKIP_PAGE is returned, the Container will stop evaluating the page when it's done with this Tag.

6. Call the release() method. This method can be used by the Tag developer to release any resources that the Tag was using. Please notice that it is up to the Container to call the release() method when seemed fit, so you can't rely on this method being called at any specific time. In theory, this method could be called 12 days after the Tag was used. For this reason, any code that must be

(54)

JSP file:

starts with

taglib

directive

<%@ taglib uri = "/taglib.tld"

prefix = "nLIB" %>

<html>

<body>

<nLIB: Helloworld />

</body>

</html>

<%@ taglib uri = "identifier"

prefix = "prefix" %>

Location of Tag Library

Distinguishes different tag libraries

(55)

Tag Library Descriptor

<?xml version=”1.0” encoding=”ISO-8859-1” ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>nLIB</shortname> <tag> <name>Helloworld</name> <tagclass>mytags.HelloWorld</tagclass> <body context>empty</body context>

Hello World Tag Library Descriptor

(56)

Tag class file

HelloWorld.class

package mytags;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagtext.*;

public class HelloWorld implements Tag {

private PageContext pagecontext; private Tag parent;

public int doStartTag() throws JSPException { return SKIP_BODY;

}

public int doEndTag() throws JSPException { try{

pageContext.getOut().write("Hello World");

} catch(java.io.Exception ex) {

throw new JSPException("IO Exception"); }

(57)

Tag class file

public void release (){}

public void setPageContext(pageContext p) { pageContext=p;

}

public void setParent(Tag t) { parent = t;

}

public void getParent() { return parent;

} }

(58)

Tag XML file

file "web.xml" (example)

describes the mapping between the taglib uri and the location of the Tag Library Descriptor (maps action tags to tag handler

classes). <web-app> <taglib> <taglib-uri> http://jakarta.apache.org/taglibs/utilitytags </taglib-uri> <taglib-location> /WEB-INF/tld/utilitytags.tld </taglib-location> </taglib> taglib-uri associated with

(59)

JSP directive to tell JSP container to use the URI

"/taglib.tld"

and the prefix

"nLIB"

<%@ taglib uri = "/taglib.tld"

prefix = "nLIB" %>

Call JSP tag:

<nLIB:Helloworld />

(60)

JSTL

JavaServer Pages Standard Tag Library

The JavaServer Pages Standard Tag Library (JSTL)

encapsulates as simple tags the core functionality

common to many Web applications.

JSTL has support for common, structural tasks such as

iteration and conditionals, tags for manipulating XML

documents, internationalization tags, and SQL tags. It

also provides a framework for integrating existing custom

tags with JSTL tags.

(61)

Servlet - JSP

Comparison

(62)

For complex pages, use a combination of both

Servlet: get request, validate and process

forward() to JSP to generate response dynamically

pass information as request attributes

Browser

URL

JSP Servlet Request Response

Servlet or JSP?

References

Related documents

Kalandoor Career DMCC Careers Dubai Customs DP World Career Dalkia Dubai Career ADGAS Career Mattex Career [email protected]. Paris Gallery

Cross this busy road and head right to walk along the road shoulder, then turn left to reenter woods at the beginning of a guardrail.. 27.1 Reach a power-line cut and turn right

The local thermal equilibrium implies several assumptions, like low fluid velocities, fast energy exchange between the phases and a smooth spatial temperature distribution.... 2.1

Gainesville State College came to the Athens area in 2003 and draws students from around the state.. The university enrolls 8,883 students and employs 551 full-time

scheme are that (i) sender and receivers carry out an efficient, bare-bone handshaking procedure to ensure reliable multicast data de- livery; (ii) the handshaking procedure is

Model (POJO/Bean) View (JSP pages) Controller (Servlet) User Instantiate/ invoke Request Forward Request/results Return results.. SSC - Communication and Networking Java

Opportunities and challenges are identified concerning the advancement and adoption of AOPs as part of an integrated approach to testing and assessing (IATA) MNs, as are

Salon International du Prêt-à-porter (Ready to wear International Fair), Paris, Porte de Versailles – January 24th to 27th. Retromobile , Paris, Porte de Versailles – February 8th