86
JSP JavaServerPages Sistemi Informativi Aziendali A.A. 2011/2012

Introduction to JSP pages

Embed Size (px)

DESCRIPTION

Introduction to the JSP technology for creating Java EE Web Applications, according to the MVC design pattern. Materiale realizzato per il corso di Sistemi Informativi Aziendali del Politecnico di Torino - http://bit.ly/sistinfo

Citation preview

Page 1: Introduction to JSP pages

JSP – JavaServerPages

Sistemi Informativi Aziendali – A.A. 2011/2012

Page 2: Introduction to JSP pages

Sommario

A.A. 2010/2011 Sistemi Informativi Aziendali 2

Basic JSP

Advanced JSP tags

Java Beans

MVC pattern

Page 3: Introduction to JSP pages

Basic JSP

JSP – JavaServerPages

Page 4: Introduction to JSP pages

The J2EE presentation tier

Servlets

Java classes that handle requests by producing responses (e.g.,

HTTP requests and responses)

JavaServer Pages (JSP)

HTML-like pages with some dynamic content.

Translated into servlets automatically

JSP Standard Tag Library (JSTL)

Set of standard components for JSP

Used inside JSP pages.

A.A. 2010/2011 4 Sistemi Informativi Aziendali

Page 5: Introduction to JSP pages

Presentation Overview

What are Java Server

Pages?

Structure of a JSP

document.

Scriplet Tag

Expression Tag

Declaration Tag

Directive Tag

JSP Tags

Processing Request

Parameters in JSPs.

A.A. 2010/2011 5 Sistemi Informativi Aziendali

Page 6: Introduction to JSP pages

Organization of the platform

Your application (servlets)

Java language

Java Servlet API

JavaServer Pages (JSP)

Your web pages

JSTL

A.A. 2010/2011 6 Sistemi Informativi Aziendali

Page 7: Introduction to JSP pages

What is JSP?

Java based technology that simplifies the developing of

dynamic web sites

JSP pages are HTML pages with embedded code that

allows to access data from Java code running on the

server

JSP provides separation of HTML presentation logic from

the application logic.

A.A. 2010/2011 7 Sistemi Informativi Aziendali

Page 8: Introduction to JSP pages

Why use JSP Technology?

Provides an extensive infrastructure for:

Tracking sessions.

Managing cookies.

Reading and sending HTML headers.

Parsing and decoding HTML form data.

Efficient:

Every request for a JSP is handled by a simple Java thread

Scalable

Easy integration with other backend services

A.A. 2010/2011 8 Sistemi Informativi Aziendali

Page 9: Introduction to JSP pages

JSP Flow..

JSP pages ―live‖ within a container that manages its

interaction:

HTTP Protocol (request, response, header)

Sessions

A.A. 2010/2011 9 Sistemi Informativi Aziendali

Page 10: Introduction to JSP pages

How it really works…

A.A. 2010/2011 Sistemi Informativi Aziendali 10

Page 11: Introduction to JSP pages

How it really works... (1/2)

Client requests a page

ending with ―.jsp‖

Web Server fires up the

JSP engine

JSP engine checks whether

JSP file is new or changed

JSP engine converts the

page into a Java servlet

(JSP parser)

JSP engine compiles the

servlet (Java compiler)

Page 12: Introduction to JSP pages

How it really works... (2/2)

Servlet Engine executes

the new Java servlet using

the standard API

Servlet‘s output is

transferred by Web Server

as a http response

Page 13: Introduction to JSP pages

Structure of a JSP file

Similar to a HTML document. Four basic tags:

Scriplet <% …java statements… %>

Expression <%= …java expression… %>

Declaration <%! …java variable declarations… %>

Directive <%@ …special jsp directives… %>

<html> <head> <title>Hello World</head> </head> <body> <h1>Hello, World</h1> It’s <%= (new java.util.Date()).toString() %> and all is well. </body> </html>

A.A. 2010/2011 13 Sistemi Informativi Aziendali

Page 14: Introduction to JSP pages

Scriptlet Tag

Two forms:

<% any java code %>

<jsp:scriptlet> ... </jsp:scriptlet>

(XML form)

Embeds Java code in the JSP document that will be

executed each time the JSP page is processed.

Code is inserted in the service() method of the generated

Servlet

<html> <body> <% for (int i = 0; i < 2; i++) { %> <p>Hello World!</p> <% } %> </body> </html>

<html> <body> <p>Hello World!</p> <p>Hello World!</p> </body> </html>

A.A. 2010/2011 14 Sistemi Informativi Aziendali

Page 15: Introduction to JSP pages

Expression Tag

<%= expr %>

<jsp:expression> expr </jsp:expression>

Expression expr is evaluated (in Java) and its value is

placed in the output.

Note: no semi-colon ―;‖ following expr

<html> <body> <p> <%= Integer.toString( 5 * 5 ) %> </p> </body> </html>

html> <body> <p>25</p> </body> </html>

A.A. 2010/2011 15 Sistemi Informativi Aziendali

Page 16: Introduction to JSP pages

Declaration Tag

<%! declaration %>

<jsp:declaration> declaration(s)</jsp:declaration>

Embeds Java declarations inside a JSP document

Code is inserted in the body of the servlet class, outside

the service method.

May declare instance variables

May declare (private) member functions

<html> <body> <%! private int accessCount = 0; %> <p> Accesses to page since server reboot: <%= ++accessCount %> </p> </body> </html>

A.A. 2010/2011 16 Sistemi Informativi Aziendali

Page 17: Introduction to JSP pages

Warning!

JSP declarations add variables in the servlet instance class

Variables shared by all threads (all requests to the same

servlet)

Until servlet container unloads servlet

Beware simultaneous access! Must use synchronized methods

<html> <body> <%! private int accessCount = 0; %> <p> Accesses to page since server reboot: <%= ++accessCount %> </p> </body> </html>

A.A. 2010/2011 17 Sistemi Informativi Aziendali

Page 18: Introduction to JSP pages

Directive Tag

<%@ directive att="value" %>

<jsp:directive.page att="val" />

Directives are used to convey special processing

information about the page to the JSP container.

page directive

include directive

<%@ page import="java.util.*" %> <%@ page contentType="text/xml" %> <%@ page errorPage="error.jsp" %>

A.A. 2010/2011 18 Sistemi Informativi Aziendali

Page 19: Introduction to JSP pages

The JSP @page Directive

import="package.class" or

import="pkg.class1,...,pkg.classN"

This lets you specify what packages should be imported. The

import attribute is the only one that is allowed to appear

multiple times.

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

contentType="MIME-Type" or contentType="MIME-Type;

charset=Character-Set"

Specifies the MIME type of the output. Default is text/html.

Example: <%@ page contentType="text/plain" %> equivalent to

<% response.setContentType("text/plain"); %>

A.A. 2010/2011 19 Sistemi Informativi Aziendali

Page 20: Introduction to JSP pages

The JSP @page Directive

session="true|false"

A value of true (the default) indicates that the predefined

variable session (of type HttpSession) should be bound to the

existing session if one exists, otherwise a new session should

be created and bound to it.

A value of false indicates that no sessions will be used, and

attempts to access the variable session will result in errors at

the time the JSP page is translated into a servlet.

A.A. 2010/2011 20 Sistemi Informativi Aziendali

Page 21: Introduction to JSP pages

The JSP @page Directive

errorPage="url"

This specifies a JSP page that should process any Throwables

thrown but not caught in the current page.

isErrorPage="true|false"

This indicates whether or not the current page can act as the

error page for another JSP page. The default is false.

A.A. 2010/2011 21 Sistemi Informativi Aziendali

Page 22: Introduction to JSP pages

The JSP @page Directive

isThreadSafe="true|false"

A value of true (the default) indicates normal servlet

processing, where multiple requests can be processed

simultaneously with a single servlet instance, under the

assumption that the author synchronized access to instance

variables.

A value of false indicates that the servlet should implement

SingleThreadModel, with requests either delivered serially or

with simultaneous requests being given separate servlet

instances.

Don‘t use it, since it reduces performance!

A.A. 2010/2011 22 Sistemi Informativi Aziendali

Page 23: Introduction to JSP pages

The JSP @page Directive

buffer="sizekb|none"

This specifies the buffer size for the jspWriter out. The default

is server-specific, but must be at least 8kb.

autoflush="true|false"

A value of true, the default, indicates that the buffer should be

flushed when it is full.

A value of false, rarely used, indicates that an exception should

be thrown when the buffer overflows.

A value of false is illegal when also using buffer="none".

A.A. 2010/2011 23 Sistemi Informativi Aziendali

Page 24: Introduction to JSP pages

The JSP @page Directive

extends="package.class"

This indicates the superclass of servlet that will be generated.

Use this with extreme caution, since the server may be using a

custom superclass already.

info="message"

This defines a string that can be retrieved via the getServletInfo

method.

language="java"

Java is both the default and the only legal choice.

A.A. 2010/2011 24 Sistemi Informativi Aziendali

Page 25: Introduction to JSP pages

The JSP @include Directive

<%@ include file="relative url" %>

Include files at the time the JSP page is translated into a servlet.

The contents of the included file are parsed as regular JSP

text, and thus can include static HTML, scripting

elements,directives, and actions.

Warning: when included files change, the page is not

automatically recompiled

<%@ include file="header.jsp" %> Only the content of a page is unique. Header and footer are reused from header.jsp and footer.jsp <%@ include file="footer.jsp" %>

A.A. 2010/2011 25 Sistemi Informativi Aziendali

Page 26: Introduction to JSP pages

JSP Comments

Regular (HTML) Comment

<!-- comment -->

Hidden (JSP) Comment

<%-- comment --%>

<html> <!-- Regular Comment --> <%-- Hidden Comment --%> <% // Java comment %> </html>

<html> <!-- Regular Comment --> </html>

A.A. 2010/2011 26 Sistemi Informativi Aziendali

Page 27: Introduction to JSP pages

Scriptlet Example

A.A. 2010/2011 27 Sistemi Informativi Aziendali

Page 28: Introduction to JSP pages

JSP Pages content

Actions

<% Any Java code... %>

Goes into the service() method

Implicit objects accessible to actions

page

out

config

session

request

application

response

pageContext

exception

A.A. 2010/2011 28 Sistemi Informativi Aziendali

Page 29: Introduction to JSP pages

Implicit Objects

request

The HttpServletRequest parameter

Mainly used for getting request parameters

response

The HttpServletResponse parameter

Rarely used in JSP (directives already to the work for us...)

out

The PrintWriter associated to the response (buffered)

out.println()

Not much used... just escape to HTML

%>html code<%

A.A. 2010/2011 29 Sistemi Informativi Aziendali

Page 30: Introduction to JSP pages

Request object- getting parameters

String getParameter(String name)

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Map getParameterMap()

Returns a java.util.Map of the parameters

Enumeration getParameterNames()

Returns an Enumeration of String objects containing the names of the parameters

String[] getParameterValues(String name)

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

More methods: http://java.sun.com/javaee/5/docs/api/

HttpServletRequest, ServletRequest

A.A. 2010/2011 30 Sistemi Informativi Aziendali

Page 31: Introduction to JSP pages

Implicit Objects (will be used with

JavaBeans)

session

The HttpSession object associated to the request

Created automatically

application

The ServletContext object

Used to share variables across all servlets in the application

getAttribute and setAttribute methods

config

The ServletConfig object

pageContext

The PageContext object

Used for sharing JavaBeans

A.A. 2010/2011 31 Sistemi Informativi Aziendali

Page 32: Introduction to JSP pages

Request Parameters

JSP provides access to the implicit object request that

stores attributes related to the request for the JSP page

as parameters, the request type and the incoming HTTP

headers (cookies, referer, etc.).

Example Request:

http://localhost/example.jsp?param1=hello&param2=world

<html> <body> <p><%= request.getParameter(“param1”) %></p> <p><%= request.getParameter(“param2”) %></p> </body> </html>

<html> <body> <p>Hello</p> <p>World</p> </body> </html> A.A. 2010/2011 32 Sistemi Informativi Aziendali

Page 33: Introduction to JSP pages

JSP Example: Hello World

1.

2.

A.A. 2010/2011 33 Sistemi Informativi Aziendali

Page 34: Introduction to JSP pages

SimpleJSP.jsp

A.A. 2010/2011 34 Sistemi Informativi Aziendali

Page 35: Introduction to JSP pages

JSP Expression Language ${el}

JSP – JavaServerPages

Page 36: Introduction to JSP pages

(Embedded) Expression language

An EL expression always starts with a ${ and ends with a

}

All EL expressions are evaluated at runtime

The EL usually handles data type conversion and null

values -> easy to use

The expression can include

literals ( ―1‖, ―100‖ etc)

variables

implicit variables

A.A. 2010/2011 36 Sistemi Informativi Aziendali

Page 37: Introduction to JSP pages

Examples

${1+2+3}

${param.Address}

A.A. 2010/2011 37 Sistemi Informativi Aziendali

Page 38: Introduction to JSP pages

EL Operators

== != < > <= >=

+ / div - *

&& and || or ! not

empty

A.A. 2010/2011 38 Sistemi Informativi Aziendali

Page 39: Introduction to JSP pages

JSP Implicit Objects

In JSP, need to be able to access information about the environment in which the page is running e.g. the parameters passed in a request for a form, the browser type of the user etc.

Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page. These objects may be accessed as built-in variables via scripting elements

The JSTL EL allows these objects to be accessed as ‗Implicit Variables‘

Implicit variable are just pre-agreed fixed variable names that can be used in JSTL Expressions

Think of as ―variables that are automatically available to your JSP page‖

A.A. 2010/2011 39 Sistemi Informativi Aziendali

Page 40: Introduction to JSP pages

Implicit Objects in Expression language

Very common implicit object is param

param refers to parameter passed in a request message (e.g.

information entered into a form by a user).

Example

${param.userName}

A.A. 2010/2011 40 Sistemi Informativi Aziendali

Page 41: Introduction to JSP pages

Advanced JSP tags

Introduzione al corso

Page 42: Introduction to JSP pages

JSP Action elements

Action elements are an important syntax element in JSP

They are represented by tags (as is HTML)

They assist JSP developers to develop in tags rather than

scriplet programming

Instead of <%, they just use the < character (like HTML)

<prefix:action_name> body </prefix:action_name>

A.A. 2010/2011 42 Sistemi Informativi Aziendali

Page 43: Introduction to JSP pages

JSP Action elements

JSP tags have a ―start tag‖, a ―tag body‖ and an ―end tag‖

The start and end tag have the same name enclosed in <

and >

The tag names have an embedded colon character ―:‖ in

them

the part before the colon (prefix) describes the type of the tag

the part after the ―:‖ is the Action Name

<prefix:action_name> body </prefix:action_name>

A.A. 2010/2011 43 Sistemi Informativi Aziendali

Page 44: Introduction to JSP pages

JSP Action elements

Tags have associated attributes (like HTML e.g. <img src =

―..‖)

Full syntax of JSP Action Elements is:

<prefix:action_name attr1 = ―value‖ attr2 = ―value2‖>

action_body

</prefix:action_name>

If the element doesn‘t have a body, can lose the end tag

and use shorthand syntax of:

<prefix:action_name attr1 = ―value‖ attr2 = ―value2‖ />

Example:

<jsp:include page="scripts/login.jsp" />

A.A. 2010/2011 44 Sistemi Informativi Aziendali

Page 45: Introduction to JSP pages

JSP Action Elements

JSP Pre-defined tags

Tag prefix: <jsp:...>

Also called Standard

Action Elements

External tag library

JSTL

Custom tag library

Tag prefix chosen by page

developer

A.A. 2010/2011 45 Sistemi Informativi Aziendali

Page 46: Introduction to JSP pages

JSP Predefined Tags

Also called JSP Standard Action Elements

<jsp:forward>

<jsp:include>

<jsp:param>

<jsp:plugin>

<jsp:useBean>

<jsp:getProperty>

<jsp:setProperty>

See «JavaServer Pages™ Specification» for detailed attributes

and values

http://jcp.org/aboutJava/communityprocess/final/jsr152/

http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/index.html

A.A. 2010/2011 46 Sistemi Informativi Aziendali

Page 47: Introduction to JSP pages

Standard JSP actions

JSP actions use constructs in XML syntax to control the

behavior of the servlet engine.

Available actions include:

jsp:include - Include a file at the time the page is requested.

jsp:useBean - Find or instantiate a JavaBean.

jsp:setProperty - Set the property of a JavaBean.

jsp:getProperty - Insert the property of a JavaBean into the output.

jsp:forward - Forward the requester to a new page.

jsp:plugin - Generate browser-specific code that makes an

OBJECT or EMBED tag for the Java plugin.

A.A. 2010/2011 47 Sistemi Informativi Aziendali

Page 48: Introduction to JSP pages

The jsp:forward Action

This action lets you forward the request to another page.

It has a single attribute, page, which should consist of a

relative URL:

a static value

a string expression computed at request time.

It emulates a new request from the browser

<jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" />

A.A. 2010/2011 48 Sistemi Informativi Aziendali

Page 49: Introduction to JSP pages

Example

Standard Action Example: <JSP: forward> tag

Stops processing of one page and starts processing the

page specified by the page attribute

Example:

<html>

<body>

Error occurred…please wait<br/>

<jsp:forward page="errorpage.jsp"/>

</body>

</html>

A.A. 2010/2011 49 Sistemi Informativi Aziendali

Page 50: Introduction to JSP pages

Forwarding with parameters

<jsp:forward page="urlSpec">

<jsp:param name="param1Name"

value="param1Value" />

<jsp:param name="param2Name"

value="param2Value" />

...

</jsp:forward>

A.A. 2010/2011 50 Sistemi Informativi Aziendali

Page 51: Introduction to JSP pages

The jsp:include Action

Unlike the include directive, which inserts the file at the

time the JSP page is translated into a servlet, this action

inserts the file at the time the page is requested:

Small penalty in efficiency

The included page cannot contain JSP code (only HTML)

Gains significantly in flexibility.

A.A. 2010/2011 51 Sistemi Informativi Aziendali

Page 52: Introduction to JSP pages

The <jsp:include> Action

Standard Action Example: <jsp:include> tag

Example:

<html>

<body>

Going to include hello.jsp...<br/>

<jsp:include page="hello.jsp"/>

</body>

</html>

Executes the included JSP page and adds its output into

the page

A.A. 2010/2011 52 Sistemi Informativi Aziendali

Page 53: Introduction to JSP pages

Include vs. Include

What‘s the difference from using the ‗include‘ directive?

<%@ include file = ‗hello.jsp‘ %>

The include directive includes the contents of another file at compilation time.

Good for including common static code e.g. header file, footer file.

Good on performance: included only once.

But, what if including dynamic common code (e.g. a navigation bar where links are read from the DB?).

Need to re-run the file each time a request is made - use jsp:include

jsp:include incorporates the output of the included JSP file at run time

A.A. 2010/2011 53 Sistemi Informativi Aziendali

Page 54: Introduction to JSP pages

jsp:param with jsp:include

Can be used to pass parameters when using <jsp:include>

or <jsp:forward>

Example

<jsp:include page="login.jsp">

<jsp:param name="user" value="smith" />

</jsp:include>

Executes a login page

jsp:param passes in username to the login page

A.A. 2010/2011 54 Sistemi Informativi Aziendali

Page 55: Introduction to JSP pages

JavaBeans

Introduzione al corso

Page 56: Introduction to JSP pages

Java Beans

Java Beans are reusable components. They are used to

separate Business logic from the Presentation logic.

Internally, a bean is just an instance of a class.

JSP‘s provide three basic tags for working with Beans:

<jsp:useBean >

<jsp:setProperty>

<jsp:getProperty>

A.A. 2010/2011 56 Sistemi Informativi Aziendali

Page 57: Introduction to JSP pages

The BEAN structure

The Java BEAN is not much different from a Java program.

The main differences are the signature methods being

used in a bean.

For passing parameters to a bean, there has to be a

corresponding get/set method for every parameter.

The class should be serializable (able to persistently save

and restore its state)

It should have a no-argument constructor

A.A. 2010/2011 57 Sistemi Informativi Aziendali

Page 58: Introduction to JSP pages

SimpleJSP.jsp - the Bean edition

A.A. 2010/2011 58 Sistemi Informativi Aziendali

Page 59: Introduction to JSP pages

The jsp:useBean Action

This action lets you load in a JavaBean to be used in the

JSP page.

This is a a very useful capability because it lets you exploit

the reusability of Java classes without sacrificing the

convenience that JSP adds over servlets alone.

The simplest syntax for specifying that a bean should be

used is:

<jsp:useBean id="name" class="package.class" />

A.A. 2010/2011 59 Sistemi Informativi Aziendali

Page 60: Introduction to JSP pages

Java Beans

To use a bean in a JSP page, three attributes must be

supplied

an id, which provides a local name for the bean

Creates a ―variable‖ used to access the bean

the bean's class name, which is used to instantiate the bean if it

does not exit

Suggestion: always use packages to help Tomcat find the class!

a scope, which specifies the lifetime of the bean.

<jsp:useBean id="bean name" class="bean class" scope = "page | request | session |application" />

A.A. 2010/2011 60 Sistemi Informativi Aziendali

Page 61: Introduction to JSP pages

Bean Scopes

There are four scopes available: page, request, session, and

application.

A page-scoped bean is available only within the JSP page and is

destroyed when the page has finished generating its output for

the request. By default all beans have page scope

A request-scoped bean is destroyed when the response is

sent.

A session-scoped bean is destroyed when the session is

destroyed.

An application-scoped bean is destroyed when the web

application is destroyed.

A.A. 2010/2011 61 Sistemi Informativi Aziendali

Page 62: Introduction to JSP pages

Bean Scopes

A.A. 2010/2011 62 Sistemi Informativi Aziendali

Page 63: Introduction to JSP pages

jsp:setProperty / jsp:getProperty

You use jsp:setProperty to give values to properties of

beans that have been referenced earlier

By default the values in jsp:setProperty is taken from a

parameter in the request with the same value.

You use jsp:getProperty to retrieve the value of a bean

property, convert it to a string, and to insert it into the

output.

You must use a <jsp:useBean> tag to declare the Bean before you can use <jsp:setProperty>

<jsp:useBean id="itemBean" ... /> ... <ul> <li>Number of items: <jsp:getProperty name="itemBean" property="numItems" /></li> <li>Cost of each: <jsp:getProperty name="itemBean" property="unitCost" /></li> </ul>

A.A. 2010/2011 63 Sistemi Informativi Aziendali

Page 64: Introduction to JSP pages

jsp:setProperty

<jsp:setProperty name="beanName"

property="propertyName" value="propertyValue" />

Sets the property of the given bean to the specified value

beanName must be the same name used in the id of

jsp:useBean

<jsp:setProperty name="beanName"

property="propertyName"

value="<%= expr %>" />

Uses a run-time expression to set a property value

A.A. 2010/2011 64 Sistemi Informativi Aziendali

Page 65: Introduction to JSP pages

jsp:setProperty

<jsp:setProperty name="beanName"

property="propertyName" param="parameterName" />

Sets the property to the value of a Request parameter (HTML

form)

If the parameter is not present, or if it is empty, no action is

taken

<jsp:setProperty name="beanName"

property="propertyName" />

Sets the property from a parameter name with the same name

of the property name

A.A. 2010/2011 65 Sistemi Informativi Aziendali

Page 66: Introduction to JSP pages

jsp:setProperty

<jsp:setProperty name="beanName" property="*" />

Automatically tries to set all (not-empty) Request parameters

A.A. 2010/2011 66 Sistemi Informativi Aziendali

Page 67: Introduction to JSP pages

jsp:getProperty

<jsp:getProperty name="beanName"

property="propertyName" />

Gets the property from the given bean

beanName must be the same name used in the id of

jsp:useBean

The value will be converted to a String and inserted in the

HTML page

A.A. 2010/2011 67 Sistemi Informativi Aziendali

Page 68: Introduction to JSP pages

SimpleJSP.jsp - the Bean edition

A.A. 2010/2011 68 Sistemi Informativi Aziendali

Page 69: Introduction to JSP pages

SimpleJSP.jsp - the Bean edition

A.A. 2010/2011 69 Sistemi Informativi Aziendali

Page 70: Introduction to JSP pages

MVC

Introduzione al corso

Page 71: Introduction to JSP pages

MVC design pattern A web application: Collects data and action

requests from users…

…elaborates/stores them…

…visualize the results

MVC – Model View Controller paradigm

The model represents the current state of the applications (with respect to a finite state machine)

The view corresponds to a presentation of the state

The controller verifies collected data and updates the model

A.A. 2010/2011 71 Sistemi Informativi Aziendali

Page 72: Introduction to JSP pages

MVC

Applications that present lots of data to the user, often

wish to separate data (Model) and user interface (View)

concerns

Changing the user interface do not impact the data

handling, and that the data can be reorganized without

changing the user interface.

The MVC design pattern solves this problem by

decoupling data access and business logic from data

presentation and user interaction.

A.A. 2010/2011 72 Sistemi Informativi Aziendali

Page 73: Introduction to JSP pages

MVC in the Java Server architecture

A.A. 2010/2011 73 Sistemi Informativi Aziendali

Page 74: Introduction to JSP pages

MVC with JSP only

[JavaServer Pages, 3rd Edition]

A.A. 2010/2011 74 Sistemi Informativi Aziendali

Page 75: Introduction to JSP pages

MVC with JSP and servlets

[JavaServer Pages, 3rd Edition]

A.A. 2010/2011 75 Sistemi Informativi Aziendali

Page 76: Introduction to JSP pages

MVC in J2EE: JSP, Servlet, EJB

[JavaServer Pages, 3rd Edition]

A.A. 2010/2011 76 Sistemi Informativi Aziendali

Page 77: Introduction to JSP pages

Serving static files

A.A. 2010/2011 Sistemi Informativi Aziendali 77

[Head First Servlets and Jsp]

Page 78: Introduction to JSP pages

Serving dynamic content, the MVC way

A.A. 2010/2011 Sistemi Informativi Aziendali 78

[Head First Servlets and Jsp]

Page 79: Introduction to JSP pages

Model persistence in MVC

A.A. 2010/2011 Sistemi Informativi Aziendali 79

Request-scope persistence

Elaborating user form data

Session-scope persistence

Remembering login levels and security

Storing user data, user preferences

Storing shopping carts, or other lightweight and non-historical

information

Application-scope persistence

Configuration parameters

Generally available information (e.g., maintenance mode)

Permanent persistence: storing in the DBMS

Page 80: Introduction to JSP pages

When the DB is the model

A.A. 2010/2011 Sistemi Informativi Aziendali 80

JavaBean components encapsulate all database access

Query methods

Execute queries and store query results within the bean

Perform checks and return validity values

Mainly used by the controller component

E.g., user.insertNewUser(), user.checkLogin(), user.fullUserList()

Result access methods

Return the java objects (or collections) of the query

Mainly used by the view component

E.g., user.getUserData(), user.getFullUserList()

Page 81: Introduction to JSP pages

General pattern

A.A. 2010/2011 Sistemi Informativi Aziendali 81

doPage

(controller) viewPage

HTML HTML

forward

http GET/POST request http response

databaseObject

(JavaBean) create

DB dbConnect

Connection

Query results connect

query

store

retrieve

Page 82: Introduction to JSP pages

Role of the JavaBean

A.A. 2010/2011 Sistemi Informativi Aziendali 82

For the Controller

Connect to database

Execute the queri(es)

Store the results

Keep the results in the

Request or Session scopes

Return success/failure

information

Forward to view

For the View

Return the results to be

displayed

Page 83: Introduction to JSP pages

Suggestions

A.A. 2010/2011 Sistemi Informativi Aziendali 83

One JavaBean for every database entity

One for every table, except for relationship tables

Some high-level entities are mapped to 2+ tables: only one

bean

CrUD: Create / Update / Delete methods

High level interface in the bean

Mapped to low level concrete SQL queries

Error check and validation before/after query

Other query methods

Store the results in a collection (eg., List, Map)

Keep the results until the bean scope expires

Page 84: Introduction to JSP pages

Java Collections Framework

A.A. 2010/2011 Sistemi Informativi Aziendali 84

Implementations

Hash

Table

Resizable

Array

Balanced

Tree

Linked

List

Hash

Table +

Linked

List

Interfaces

Set HashSet TreeSet LinkedHas

hSet

List ArrayList LinkedList

Deque ArrayDeq

ue LinkedList

Map HashMap TreeMap LiskedHas

hMap

http://download.oracle.com/javase/6/docs/tech

notes/guides/collections/index.html

Page 85: Introduction to JSP pages

Caching

A.A. 2010/2011 Sistemi Informativi Aziendali 85

A request-scoped bean does no caching of the data returned

Data is used once by the view, then discarded

A session- or application-scoped bean might implement caching policies

Reducing queries to get information by reusing previous results

Reducing queries to add/modify information by delaying update operations

Critical: maintaining consistency between DB contents and bean results

Best managed by existing ORM [Object-Relationan Mapping] frameworks (e.g., Hibernate)

Page 86: Introduction to JSP pages

Licenza d’uso

A.A. 2010/2011 Sistemi Informativi Aziendali 86

Queste diapositive sono distribuite con licenza Creative Commons ―Attribuzione - Non commerciale - Condividi allo stesso modo 2.5 Italia (CC BY-NC-SA 2.5)‖

Sei libero: di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,

rappresentare, eseguire e recitare quest'opera

di modificare quest'opera

Alle seguenti condizioni: Attribuzione — Devi attribuire la paternità dell'opera agli autori originali

e in modo tale da non suggerire che essi avallino te o il modo in cui tu usi l'opera.

Non commerciale — Non puoi usare quest'opera per fini commerciali.

Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una licenza identica o equivalente a questa.

http://creativecommons.org/licenses/by-nc-sa/2.5/it/