• Nu S-Au Găsit Rezultate

“Classical” Web Components

N/A
N/A
Protected

Academic year: 2022

Share "“Classical” Web Components"

Copied!
41
0
0

Text complet

(1)

Java Technologies

Web Components

(2)

“Classical” Web Components

Servlets

Web Filters

Web Listeners

– Asynchronous Servlets

Java Beans

Java Server Pages (JSP)

Custom Tag Libraries (CTL)

Java Standard Tag Library (JSTL)

(3)

Java Server Pages (JSP)

“Those who do not remember their past are condemned to repeat their mistakes”

George Santayana

(4)

JSP - The Context

The Presentation Layer of a Web App

– the graphical (web) user interface

– frequent design changes

– usually, dynamically generated HTML pages

Should we use servlets? → No (not directly)

– difficult to develop and maintain (the view)

– lack of flexibility

– lack of role separation: design → designer

(5)

Example: HelloServlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Hello extends HttpServlet {

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

response.setContentType("text/html");

PrintWriter out = new PrintWriter(response.getWriter());

out.println("<html>" +

"<head><title>Welcome!</title></head>" + "<body>" +

"<h1><font color=\"red\"> Welcome! </font></h1>" +

"<h2>Current date and time:" + new java.util.Date() + " </h2>" + "</body>" + "</html>");

out.close();

} }

(6)

Example: hello.jsp

<html>

<head>

<title>Welcome!</title>

</head>

<body>

<h1><font color="red"> Welcome! </font></h1>

<h2>Current date and time: <%= new java.util.Date() %> </h2>

</body>

</html>

(7)

The Concept

Standard component to create the presentation, that conforms to

View – Helper design pattern

(8)

JavaServer Pages (JSP)

The “classical” solution to create web content easily that has both static and dynamic

components → Web pages

Provides a natural, declarative, presentation oriented approach to creating static content

→ Templates

Are based on and benefit from all the dynamic capabilities of Java Servlet technology

→ Every JSP is actually a servlet

A first (small) step towards the role separation

(9)

The main features of JSP

A JSP page is a text document that contains:

static data (template) (HTML, SVG, WML, etc.)

JSP elements, which construct the content

JSP elements may be:

JSP tags

scriptles (code sequences written in Java...)

JSP uses an expression language for accessing server-side objects

The source files may be .jsp, .jspf, .jspx

(10)

The Life Cycle of a JSP Page

(11)

Translation Phase

//Example taken from Apache Tomcat application server

//This is the source file of the servlet generated for hello.jsp package org.apache.jsp;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

public final class hello_jsp

extends org.apache.jasper.runtime.HttpJspBase

implements org.apache.jasper.runtime.JspSourceDependent { ...

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws java.io.IOException, ServletException { ...

out.write("<HTML>");

...

out.write("</HTML>");

} }

implements javax.servlet.Servlet

(12)

JSP Syntax

<%-- Hello World example, not again ... --%>

<%@ page language="java" contentType="text/html;

pageEncoding="UTF-8"%>

<html>

<head> <title>First JSP</title> </head>

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

<%@ include file="header.html" %>

<%! String message = "Hello World"; %>

<body>

<%

for(int i=1; i<=4; i++) {

out.println("<H" + i + ">" + message + "</H" + i + ">");

}

%>

<!-- Page generated at: <%= new Date() %> -->

</body>

</html>

JSP Directives

JSP Expression

JSP Comment

JSP Declaration

JSP Scriptlet

(13)

Model – View – Controller

(14)

Custom Tag Libraries (CTL)

“Code reuse is the Holy Grail of Software Engineering.”

Douglas Crockford

(15)

CTL - The Context

JavaServer Pages offer a standard solution to create web content dynamically using JSP elements: JSP tags, scriptles, etc.

JSP are used to create the view of the application (the presentation layer)

Presentation → Designer, not Programmer

How can we generate dynamic content without writing Java code?

– The first step: JSP Standard Actions

(jsp:useBean, jsp:forward, jsp:include, etc)

(16)

The Concept

We need a component that:

Encapsulates various types of non-standard dynamic functionalities such as:

– generating an HTML table with available products

– extracting some data from an XML document, etc.

Can be used inside JSP in a similar manner to the standard actions

– the programmer writes the functionality

– the designer acceses the functionality in a declarative fashion (using a tag)

Promotes code reusability (libraries)

(17)

Separation of Concerns (Soc)

A design principle for separating a system into distinct sections, such that:

– each section addresses a separate concern

– the overlapping should be minimal

Edsger W. Dijkstra: "On the role of scientific thought" (1974)

– "focusing one's attention upon some aspect"

– “the only available technique for effective ordering

of one's thoughts”

(18)

Custom Tags in JSP

A custom tag is a user-defined JSP element

The object that implements a custom tag is called a tag handler

class (programmatically)

tag file (JSP fragment)

A tag is invoked in a JSP file using XML syntax:

<prefix:tagName>

Body

</prefix:tagName>

When a JSP is translated into a servlet, the tag

is converted to operations on the tag handler.

(19)

Custom Tag Features

Customized by means of attributes passed from the calling page

Pass variables back to the calling page

Access all the objects available to JSP pages

Communicate with each other

Be nested within one another and communicate by means of private variables

Distributed in a tag library

(20)

Creating a Tag Handler

public class HelloTagHandler extends SimpleTagSupport { /**

* Called by the container to invoke this tag. The implementation of this method is provided by the tag library developer, and handles all tag processing */

@Override

public void doTag() throws JspException, IOException { // Create dynamic content

JspWriter out = getJspContext().getOut();

out.print("Hello World from Infoiasi!");

} }

(21)

The Tag Library Descriptor (TLD)

Defines a mapping between tag handlers (classes) and tag names

<taglib>

<tlib-version>1.0</tlib-version>

<short-name>mylibrary</short-name>

<uri>/WEB-INF/tlds/mylibrary</uri>

<tag>

<name>hello</name>

<tag-class>HelloTagHandler</tag-class>

<description> Displays the Hello World message (again) </description>

<body-content>empty</body-content>

</tag>

</taglib>

(22)

Using the Custom Tag

<b>Somewhere, inside a JSP</b>

<p>

<%@ taglib uri="/WEB-INF/tlds/mylibrary"

prefix="say" %>

<say:hello/>

Use the taglib directive to specify the tag library

Use the custom tag

(23)

Java Standard Tag Libraries (JSTL)

“I believe in standardizing tag libraries :)

I do not believe in standardizing human beings”.

Albert Einstein

(24)

JSTL - The Context

JSP are used to create the view

Custom tags are user-defined JSP elements:

– encapsulate functionalities

– promote reusability and role separation

– implemented using

classes (handlers): by programmers

JSP → tag files: by designers...

How can we generate dynamic content in a

tag file without writing Java code?

(25)

The Concept

We need a solution to:

Allow the designer to implement custom tags in the form of tag files.

Simplify the creation of JSP pages

– accessing the model (data stored in beans)

– controlling the execution of a page

– etc.

Standardize the design elements.

Optimize the execution of JSP pages.

(26)

Example

In a JSP (page or tag file), we verify if the user has a specific role, using a scriptlet:

<%

User user = (User) session.getAttribute("user");

if (user.getRole().equals("member"))) {

%>

<p>Welcome, member!</p>

<% } else { %>

<p>Welcome, guest!</p>

<% } %>

It is difficult to provide a custom tag handler for every situation.

awful...

(27)

Example (cont.)

A more “appealing” solution would be:

<c:choose>

<c:when test="${user.role == ’member’}">

<p>Welcome, member!</p>

</c:when>

<c:otherwise>

<p>Welcome, guest!</p>

</c:otherwise>

</c:choose>

Expression Languge

Standard Tags

(28)

Expression Language (EL)

Access application data stored in JavaBeans components

Create expressions arithmetic and logical in a intuitive manner:

${ (10 % 5 == 0) or ( 2 > 1) ? 'yes' : 'no' }

${ header["user-agent"] }

No programming skills required

When the JSP compiler “sees” the ${} form in

an attribute, it generates code to evaluate the

expression and substitues the resulting value.

(29)

EL Syntax

Literals: true, false, null, “a”, 'b', 123, 9.99

Variables

PageContext.findAttribute(variable)

page → request → session → application

variable.property or variable[property]

Operators: as usual plus:

eq, ne, ge, le, lt, gt, mod, div, and, or, not, empty

Implicit Objects:

param, request, response, session, servletContext

pageScope, requestScope, sessionScope, applicationScope

header, cookie, initParam, etc.

(30)

Standard Tag Libraries (JSTL)

A collection of useful JSP tags which

encapsulates functionalities common to many JSP applications.

JSTL has support for:

Core Tags

Formatting tags

XML tags

SQL tags

JSTL Functions

(31)

Core Tags (c)

Core tags are the most frequently used JSTL tags.

<c:set var="message" scope="page" value="Hello JSTL!"/>

<c:out value="${message}" default="Hello World!"/>

<c:forEach var="item" items="${sessionScope.cart.items}">

<c:out value="${item}"/> <br/>

</c:forEach>

<c:import url="someFile.csv" var="content" />

<c:forTokens var="item" items="${content}" delims=",">

<c:out value="${item}"/> <br/>

</c:forTokens>

<c:if test="${empty session.user}">

<c:redirect url="login.jsp"/>

</c:if>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

(32)

Formatting Tags (fmt)

Used to format and display text, the date, the

time, and numbers for internationalized Web sites.

<jsp:useBean id="now" class="java.util.Date" />

<fmt:setLocale value="ro-RO" />

<fmt:formatDate value="${now}"

type="both"

dateStyle="full" timeStyle="full"/>

<fmt:setLocale value="ro"/>

<fmt:setBundle basename="somepackage.Messages"

var="msg"

scope="page"/>

<fmt:message key="hello"

bundle="${msg}"/>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

I18N L10N

(33)

XML Tags (x)

Create and manipulate XML documents: parsing XML, transforming XML data, and flow control

based on XPath expressions.

<c:import url="agenda.xml" var="xml" />

<x:parse doc="${xml}" var="agenda" scope="application" />

<x:set var="friend"

select="$agenda/friends/person[@id=$param:personId]" />

<x:out select="$friend/name"/></h2>

<x:forEach var="friend"

select="$agenda/friends/person" />

<x:out select="$friend/name" />

</x:forEach>

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<c:import url="agenda.xml" var="xml" />

<c:import url="style.xsl" var="style" />

<x:transform source="${xml}" xslt="${style}"/>

(34)

SQL Tags (sql)

Tags for interacting with relational databases:

connect, read (query), update, delete.

<sql:setDataSource var="timtable"

url="jdbc:sybase:Tds:localhost:2638?ServiceName=TimetableDB"

driver="com.sybase.jdbc4.jdbc.SybDataSource"

user="DBA" password="sql"/>

<sql:setDataSource var="timetabe"

dataSource="jdbc/TimetableDB" />

<c:set var="roomId" value="C401"/>

<sql:query var="rooms" dataSource="${timetable}"

sql="select * from rooms where code = ?" >

<sql:param value="${roomId}" />

</sql:query>

<c:out value="${rooms.rowCount}"/>

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:update dataSource="${timetable}">

update rooms set address=’la subsol’ where code=’C112’

</sql:update>

(35)

Alternatives to JSP

“The absence of alternatives clears the mind marvelously.”

Henry Kissinger

(36)

Template Engines

The Context → generate documents

– reports, emails, sql scripts, source files, etc.

– web pages

We need a generic solution to:

– specify the template

– specify the data

generate the document

(37)

MVC Frameworks

Template Language → View

Data (Beans) → Model

Runtime Engine → Controller

(38)

Example: The Template File

Static text + Template Languge (simple syntax)

<html>

<head> <title> Welcome </title> </head>

<body>

<h1>Welcome ${user}!</h1>

<p>Our latest product:

<a href="${latestProduct.url}">${latestProduct.name}</a>!

<p>All the products:

<#list products as product>

<li>${product.name}, ${product.price}

<#if product.stock == 0>

Empty stock!

<#if>

</#list>

</body>

</html>

(39)

Example: The Model

(root) |

+- user = "Big Joe"

|

+- latestProduct |

+- url = "products/greenmouse.html"

|

+- name = "green mouse"

...

Map<String, Object> data = new HashMap<String,Object>();

User user = new User("Big Joe");

data.put("user", user);

Product product = new Product();

product.setName("green mouse");

product.setUrl("products/greenmouse.html");

data.put("latestProduct", product);

data.put("today", new java.util.Date());

(40)

Merging the View and the Model

// Initialization: where are my templates?

Configuration cfg = new Configuration();

cfg.setDirectoryForTemplateLoading(new File("someFolder"));

// set global variables if you need to

cfg.setSharedVariable("version", "0.0.1 beta");

// Prepare the data

Map<String,Object> data = ... ; // Choose a template

Template template = cfg.getTemplate("someTemplate.ftl");

// Specify the output stream

String filename = "someFile.html"

Writer out = new BufferedWriter(new FileWriter(filename));

//Do it: process, merge, etc.

template.process(data, out);

out.close();

(41)

Using FreeMarker in a Web App

Register the FreeMarker Servlet

<servlet>

<servlet-name>freemarker</servlet-name>

<servlet-class>

freemarker.ext.servlet.FreemarkerServlet </servlet-class>

<init-param>

<param-name>TemplatePath</param-name>

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

</init-param> ...

</servlet>

Map the requests

<servlet-mapping>

<servlet-name>freemarker</servlet-name>

<url-pattern>*.ftl</url-pattern>

</servlet-mapping>

Any request (.ftl) goes to the servlet

http://localhost:8080/myapp/products.ftl

Referințe

DOCUMENTE SIMILARE

1 Department of Physical Medicine and Rehabilitation, National Taiwan University Hospital, Bei-Hu Branch and National Taiwan University College of Medicine, Taipei, Taiwan, 2

Locations of the tibial nerve, popliteal artery, vein (b), and medial sural cutaneous nerve (c), and safe angles for nee- dle insertion (d).. n: tibial nerve, a: popliteal artery,

1. Enlarged spinoglenoid notch veins causing suprascapular nerve compression. Dynamic ultrasonogra- phy of the shoulder. Lafosse L, Tomasi A, Corbett S, Baier G, Willems K,

ductal orifice, and presence of a sphincter-like mecha- nism in the distal 3 cm of the duct [2].In the last four dec- ades, 22 cases with foreign bodies in the submandibular

1 Department of Physical Medicine and Rehabilitation, National Taiwan University Hospital, Bei Hu Branch and National Taiwan University College of Medicine, Taipei, Taiwan,

Transverse (a) and longitudinal (b) transvaginal ultrasound exhibit an isoechoic solid mass measuring 4 cm in size, with mul- tiple intralesional echogenic foci (arrows) and

Because the main technologies used to develop the system are web-based, the searching modules implement semantic web technologies combined with intelligent

According to our previous investigations it seems that tolerance, whether regarded as a political practice or a philosophical or moral principle, is a strategy (or tactics) of one