Vous êtes sur la page 1sur 129

05/04/2007

Java Server Pages (JSP)


Basics

Today, we are going to talk about basic concept of JSP, Java


Server Pages. Along with Servlet, JSP is one of the most widely
used technologies for creating dynamic web contents. As we will
see later, JSP and Servlet are complementary technologies.

05/04/2007

Disclaimer & Acknowledgments


?

Even though Sang Shin and Sameer Tyagi are full-time


employees of Sun Microsystems, the contents here are
created as their own personal endeavor and thus does
not reflect any official stance of Sun Microsystems.
Sun Microsystems is not responsible for any
inaccuracies in the contents.
Acknowledgments

Large portion of slides, speaker notes, and example code of


this presentation are created from JSP section of Java WSDP
tutorial written by Stephanie Bodoff of Sun Microsystems
Many slides are borrowed from Servlet/JSP codecamp
material authored by Doris Chen of Sun Microsystems
Some example codes and contents are borrowed from Core
Servlets and JavaServer Pages book written by Marty Hall
2

05/04/2007

Revision History
?
?
?

12/24/2002: version 1 created by Sameer Tyagi


01/12/2003: version 2 revised by Sang Shin with speaker notes
05/13/2003: version 3 revised (Sang Shin)

05/04/2007

Sub-topics of JSP

Before I proceed, let me talk about which parts of JSP will be dealt
with in this two hour session.

05/04/2007

Sub-topics of JSP
?
?
?
?

JSP Basic
JavaBeans for JSP
Custom tags
JSP Standard Tag Library (JSTL)

We will deal with only the first two topics in this


session

The topic of JSP can be divided into 4 sub-topics: first, JSP basics, second,
how JavaBeans are used within a JSP page, and third custom tags, which
are special kind of Java components specifically geared for JSP
technology, and finally JSP standard tag library, which is a standard set of
custom tags every J2EE compliant app server has to support.
In this two hour session, we are going to deal with only the first two subtopics - JSP basics and JavaBeans for JSP.
And the latter two topics, custom tags and JSP standard tag library (JSTL)
will be dealt with either later in this course or in advanced J2EE course.

05/04/2007

Advanced Topics of Servlet/JSP


?
?
?
?
?

MVC (Model-View-Controller) Pattern


Model 2 Framework
Apache Struts
Java Server Faces (JSF)
Other frameworks

Another important topic people talk about these days are Web application frameworks,
which are based JSP and Servlet technologies. And this slide shows the list of those
frameworks.
I am sure many of you have heard of MVC pattern or MVC architecture. It stands for
Model View Controller and deals with what would be the best architecture at web-tier
in terms of reusability of code, robustness of design and implementation,
maintainability of code, and so on. And the MVC design pattern basically sums up the
knowledge and best practice guidelines that people have learned so far.
Among the MVC design pattern, a so-called Model2 architecture is the one everybody
agrees is the framework that provides best code reusability, best maintenability. In
Model 2 architecture, a servlet functions as a controller or a dispatcher while JSP pages
are used for handing the View.
Now there are several actual frameworks that are based on Model 2 architecture. And
the most popular one people use is Apache Struts. And Java Server Faces is a Java
Initiative in this area.
Then there are other frameworks such as Echo or Tapastry.
Again, we will deal with these topics in a bit more detail in Advanced J2EE
programming course.

05/04/2007

Agenda
?
?
?
?

?
?

?
?

JSP in big picture of Java EE


Introduction to JSP
Life-cycle of JSP page
Steps for developing JSP-based Web
application
Dynamic contents generation techniques in JSP
Invoking Java code using JSP scripting
elements
JavaBeans for JSP
Error handling
7

So this is the list of topics that I am going to talk about in this two hour
session. First, I will talk about where JSP fits in the big picture of J2EE
architecture. And I will give a quick introduction on how JSP works. And
we will talk about life-cycle of JSP pages.
Then I will spend some time talking about how you develop JSP-based
web application. Then I will talk about anatomy of JSP page, that is, what
things make up a JSP page. And then I will talk about how JavaBeans are
used within the JSP page. Finally, I will talk about how error handling can
be done with JSP pages.

05/04/2007

JSP in a
Big Picture of Java EE
8

OK, let's talk about where JSP fits in from a big picture perspective of
J2EE architecture.

05/04/2007

JSP & Servlet in


Java EE Architecture
An extensible Web technology that uses template data,
custom elements, scripting languages, and server-side
Java objects to return dynamic content to a client.
Typically the template data is HTML or XML elements.
The client is often a Web browser.

Java Servlet A Java program that


extends the functionality of a Web
server, generating dynamic content
and interacting with Web clients
using a request-response
paradigm.

This picture describes what roles JSP and Servlet plays in J2EE
architecture. Servlet is a program that extends the functionality of a web
server by generating dynamic contents and interacting with web clients
using request-response paradigm.
JSP is an extensible web technology that uses template data, custom
elements, string languages, and server-side Java objects to return dynamic
contents to a client. Typically the template data or static data is HTML or
XML elements.

05/04/2007

What do you mean by Static & Dynamic Contents?


?

Static contents

Typically static HTML page


Same display for everyone

Dynamic contents

Contents is dynamically generated based on


conditions
Conditions could be
?
?
?

User identity
Time of the day
User entered values through forms and selections

Examples
?

Etrade webpage customized just for you, my Yahoo

10

I've been saying on and off that JSP and servlet technologies are for generating
and displaying dynamic contents (as opposed to static contents). Now for those
of you who are not familiar with servlet or JSP may wonder what I mean by static
contents and dynamic contents. So let me clarify these terms a bit before I move
on.
Static contents are basically HTML pages whose contents do not change
regardless of the external conditions. For example, our class website is in fact an
example of static contents. It does not contain any dynamically generated content
even a counter that counts how many people have accessed the page. In other
words, it displays the same information for everyone regardless who accesses the
page.
The dynamic contents, on the other hand, are dynamically generated based on
external conditions such as user identity or time of the day or values that are
entered by an end user through form-based input or choice selection the user has
made. Examples of dynamic contents are personally customized ETrade webpage
or Personal Yahoo webpage. Based on your identity, the web server dynamically
generate customized information, for example, your stock account balance or
stock transactions you performed and so on. And the web server uses
technologies such as servlet or JSP for generating these dynamic contents.
10
By the way, a typical web application uses both static and dynamic contents
together.

05/04/2007

JSP & Servlet as Web Components

11

This picture shows where JSP and Servlet based web components fit in a
multi-tier J2EE architecture. As you can see, the JSP and servlet are
running inside a Web container performing dynamic contents generation.
As for business logic processing, JSP and servlets could be invoking
services offered by EJB beans that are running in EJB container or they
might perform the business logic processing themselves.

11

05/04/2007

What is JSP Page?


?

A text-based document capable of returning


both static and dynamic content to a client
browser
Static content and dynamic content can be
intermixed
Static content

HTML, XML, Text

Dynamic content

Java code
Displaying properties of JavaBeans
Invoking business logic defined in Custom tags

12

So what is a JSP page? JSP page is simply a text-based document capable


of returning both static and dynamic content to a client browser. And the
static and dynamic content are typically intermixed.
Static content can be made of HTML tags, XML tags, or plain Text content
while dynamic content can be generated by Java code, displaying
properties of JavaBeans or invoking business logic defined in custom tags.
Typically a JSP page is made of static template usually in the form HTML
page in which Java code, JavaBeans, custom tags are used for dynamic
contents generation.

12

05/04/2007

A Simple JSP Page


(Blue: static, Red: Dynamic contents)
<html>
<body>
Hello World!
<br>
Current time is <%= new java.util.Date() %>
</body>
</html>

13

So this is an example of a very simple JSP page. Here the things that are
colored in blue are static contents while the things in red color are JSP
elements that performs dynamic content generation.
In this example, the current time and date is dynamically generated and
displayed, thus reflecting the current time and date, while the rest of the
page is static.

13

05/04/2007

Output

14

This is the display when you access the previous JSP page. So depending
on when you access the page, the time and date will be different while the
Hello World Message would remain the same.
Now in this page, the Hello, World greeting message is displayed in
English. But if you want to display the greeting message in local language
or display different greeting depending on the time of the day, for example,
Good morning during morning period or Good afternoon during the
afternoon period, then even that greeting has to be generated as dynamic
contents.

14

05/04/2007

JSP
Servlets
HTML code in
Java
? Not easy to
author

JSP
Java-like code in
HTML
? Very easy to
author
? Code is compiled
into a servlet
?

15

This is something we talked about in servlet session. Just to rehash the


difference between the two technologies, let's compare them one more time
here.
In servlet, the HTML generation logic is in the form of Java code while in
JSP, the HTML page can be represented as HTML tags. In servlet,
because HTML page has to be generated inside Java code, it is rather hard
to author web pages. And JSP is designed to make this webpage
authoring process easier for web page designers because they don't have to
know how to write Java code in most cases.
Now I want to make sure you understand that JSP and servlet are very
closely related and complementary. In fact, JSP pages are internally
translated into servlet code when they get deployed. And I will talk about
this aspect later on one more time.

15

05/04/2007

JSP Benefits
?
?

Content and display logic are separated


Simplify web application development
with JSP, JavaBeans and custom tags
Supports software reuse through the use
of components (JavaBeans, Custom
tags)
Automatic deployment

?
?

Recompile automatically when changes are


made to JSP pages

Easier to author web pages


Platform-independent

16

So just recap the benefits of using JSP...


First, under JSP architecture, contents and display logic(or presentation logic)
are separated.
Consequently using JSP, web application development can be simplified
because business logic is captured in the form of JavaBeans or custom tags
while presentation logic is captured in the form of HTML template..
Because the business logic is captured in component forms, they can be reused
in other Web applications.
Most web containers will automatically recompile newly modified JSP pages.
And again for web page authors, dealing with JSP page is a lot easier than
writing Java code.
And just like Servlet technology, JSP technology runs over many different
platforms.

16

05/04/2007

Why JSP over Servlet?


?

Servlets can do a lot of things, but it is


pain to:
Use those println() statements to generate
HTML page
Maintain that HTML page

No need for compiling,


packaging,CLASSPATH setting

17

Jus to summarize the reason of usage of JSP over Servlet. In servlet, in


order to create HTML pages, you have to use println()statements which is
really a pain.
Also because servlet is Java program, whenever you make a change, you
have to recompile and redeploy, which is not really convenient. And JSP
correct both of these problems of Servlet.

17

05/04/2007

Do I have to Use JSP over Servlet


or vice-versa?
?

No, you want to use both leveraging the


strengths of each technology

Servlet's strength is controlling and dispatching


JSP's strength is displaying

In a typically production environment, both


servlet and JSP are used in a so-called
MVC (Model-View-Controller) pattern

Servlet handles controller part


JSP handles view part
18

OK, we talked about benefits of using JSP over servlet.


Now some of you want to ask Do I have to use JSP over Servlet for all my web
application development? The answer is emphatic no. The strengths and for that
matter the weaknesses of these two technologies are different. That is, they are
designed for different purpose. And you want to leverage the strength of each
technologies in your application.
Let's talk about Servlet first. Because it gives the web application designer a great
control in the form of a Java program, its strength is in the area of controlling and
dispatching. For example, if you want to display a different contents depending on
who is the caller or input parameter value or time of day or based on some business
logic processing, it is somewhat easier to express that condition in a program. Now
after controlling and dispatching is done, you can choose which HTML page (or XML
or WML page) can be displayed. The strength of JSP is again displaying HTML or
XML pages.
So in a typical production environment, people use servlet and JSP technologies
together in a so-called MVC (Model-View-Controller) pattern, where servlet plays the
role of Controller while JSP plays the role of View.

18

05/04/2007

JSP
Architecture
19

Now let's talk about JSP architecture.

19

05/04/2007

Web Application Designs

20

This picture shows the evolution of web application starting from a


simplest one which then evolves into more sophisticated and more robust
design.
So in the first phase of the evolution, just static HTML pages were used to
display static information. Then in the subsequent evolution phase,
dynamic contents generation technologies such as CGI initially, then
servlet and JSP are introduced to generate and display dynamic contents
along with static contents.
When you are using JSP pages, you can use only the basic features that
come with it. Or you can leverage more sophisticated features such as
component-based dynamic contents generation, for example, leveraging
JavaBeans or custom tags, which provide more reusable, more
maintainable, more flexible development and deployment options.
Then in a more sophisticated environment, people use so-called template
based design or eventually they might want to delegate their business logic
processing to EJB tier.

20

05/04/2007

Separate Request processing From


Servlet
Presentation
Request processing

Pure Servlet

Public class OrderServlet {


public void doGet(){

if(bean.isOrderValid(..)){
bean. saveOrder(.);
forward(conf.jsp);
}

Public class OrderServlet {


public void doGet(){
if(isOrderValid(req)){
saveOrder(req);
out.println(<html>);
out.println(<body>);

private void isOrderValid (.){

JSP
presentation

private void saveOrder(.){

<html>
<body>
<ora: loop name =order>
..
< /ora :loop>
<body>
</html>

JavaBeans

isOrderValid( )
Business logic

saveOrder( )
21

I mentioned several times already that one of the distinguished features of


JSP is the separation of contents generation logic from presentation logic.
Here the contents generation includes business logic processing.
I also mentioned that in a typical production environment, both servlet and
JSP are used together in which servlet is used for controlling and
dispatching while JSP page is used for displaying. This slide shows
exactly that scenario.
On the left, you have a pure servlet based design where contents generation
and presentation logic are all handled within a servlet.
Now on the right side of the picture where servlet and JSP are used
together, servlet performs controlling and dispatching while JSP is used for
displaying. How does servlet select which JSP pages to be displayed? It
uses forward() method in which a JSP page is specified as a page to be
displayed. And that is what is shown in the servlet code on the top box of
the right hand side.

21

05/04/2007

JSP Architecture

22

This picture shows JSP architecture. When a client sends a HTTP request
to a JSP page, the JSP page will be translated and compiled into a
corresponding servlet class. Or in many web containers, the JSP pages are
compiled into servlet classes when they are deployed. Once it is compiled
into a servlet class, then it follows the same life-cycle of a servlet.

22

05/04/2007

Life-Cycle of a JSP
Page
23

OK. Let's talk about the life cycle of a JSP page, that is, how a deployed JSP
page gets translated and compiled into a corresponding servlet and then how
the resulting servlet instance serves the client requests.

23

05/04/2007

How Does JSP Work?


User Request
Server
File JSP
Changed
?
Create Source
Compile
Execute Servlet
24

When a HTTP request is mapped to a JSP page, it is handled by a


special built-in servlet (that is provided by a container) that first checks
whether the JSP page's servlet is older than the JSP page. If it is, the
container translates the JSP page into a servlet Java code and compiles
the servlet code into servlet class. And this is done automatically by
the container. This is one of the advantages of using JSP over servlet
from deployment standpoint.

24

05/04/2007

JSP Page Lifecycle Phases


?
?
?

Translation phase
Compile phase
Execution phase

25

So the lifecycle of a JSP page can be divided into three phases: (1)
translation phase in which a JSP page gets translated into a servlet code,
(2) compilation phase in which servlet code gets compiled, (3) then
execution phase in which servlet instance then serves client request.
Usually translation and compilation phases occur together.

25

05/04/2007

Translation/Compilation Phase
?

?
?

JSP files get translated into servlet source


code, which is then compiled
Done by the container automatically
The first time JSP page is accessed after it
is deployed (or modified and redeployed)
For JSP page pageName, the source code
resides

<AppServer_HOME>/work/Standard
Engine/localhost/context_root/pageName$jsp.java
<AppServer_HOME>/work/Standard
Engine/localhost/date/index$jsp.java

26

So in translation/compilation phase, a JSP page gets translated and compiled


automatically if there is no complied class already. So if you deploy your JSP page
for the first time, or if you modified the JSP page, then translation and compilation
will occur. This is why sometimes you observe the response time takes a bit longer
when you access a relatively sophisticated JSP page for the first time, because the
container has to do translation and compilation before it can handle your request.
Usually in order to reduce this first-time delay, developers call their JSP pages at the
time of deployment or in many cases the container might do that anyway.
So for a JSP page named pageName, under Tomcat, the translated source code for a
JSP page's servlet is kept in the file:
<JWSDP_HOME>/work/Standard Engine/
localhost/context_root/pageName$jsp.java
For example, the source for the index page (named index.jsp) for the date localization
example discussed at the beginning of the this session would be named:
<JWSDP_HOME>/work/Standard Engine/localhost/date/index$jsp.java

26

05/04/2007

Translation/Compilation Phase
?

Static Template data is transformed into code


that will emit data into the stream
JSP elements are treated differently

Directives are used to control how Web container


translates and executes JSP page
Scripting elements are inserted into JSP page's servlet
class
Elements of the form <jsp:xxx .../> are converted into
method calls to JavaBeans components

27

Now how does translation work?


During the translation phase, each type of data in a JSP page is treated differently.
That is, static data will be treated differently from dynamic contents generation
elements. Static data (this is sometimes called as template data) is transformed
into Java code that will emit the data into the output stream which returns data to
the client.
However, JSP elements, which are typically used for dynamic contents
generation,are treated as follows:
* Directives are used to control how the Web container translates and executes the
JSP page.
* Scripting elements are directly inserted into the JSP page's servlet class
unmodified.
* Elements of the form <jsp:XXX ... /> are converted into method calls to
JavaBeans components or invocations of the Java Servlet API.
We will talk about these in detail in the rest of this session. So if you don't
understand what I mean here, don't worry about it.

27

05/04/2007

JSP Lifecycle Methods during


Execution Phase

28

Once the page has been translated and compiled, the JSP page's servlet for the
most part follows the servlet life cycle as following:
1. If an instance of the JSP page's servlet does not exist, the container Loads the
JSP page's servlet class
2. Container then creates an instance of the servlet class
3. Container then initializes the servlet instance by calling the jspInit method
4. Container invokes the _jspService() method, passing a request and response
object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy()
method.

28

05/04/2007

Initialization of a JSP Page


?

Declare methods for performing the


following tasks using JSP declaration
mechanism

Read persistent configuration data


Initialize resources
Perform any other one-time activities by overriding
jspInit() method of JspPage interface

29

You can customize the initialization process to allow the JSP page to
read persistent configuration data, initialize resources, and perform any
other one-time activities by overriding the jspInit() method of the
JspPage interface.

29

05/04/2007

Finalization of a JSP Page


?

Declare methods for performing the


following tasks using JSP declaration
mechanism

Read persistent configuration data


Release resources
Perform any other one-time cleanup activities by
overriding jspDestroy() method of JspPage
interface

30

You release resources using the jspDestroy() method. The methods


are defined using JSP declarations.

30

05/04/2007

Example: initdestroy.jsp
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%-- Declare initialization and finalization methods using JSP declaration -%>
<%!
private BookDBAO bookDBAO;
public void jspInit() {
// retrieve database access object, which was set once per web
application
bookDBAO =
(BookDBAO)getServletContext().getAttribute("bookDB");
if (bookDBAO == null)
System.out.println("Couldn't get database.");
}
public void jspDestroy() {
bookDBAO = null;
}
%>

31

The bookstore example page initdestroy.jsp defines the jspInit()


method in which a database access object called BookDBAO is
retrieved from the ServletContext object and then uses it to access the
bookstore database.
When the JSP page is to be removed, the jspDestroy() method releases
the BookDBAO variable.
In this example, you probably have noticed that the jspInit() method
does not create itself a connection to database. Instead it tries to get a
reference to a previously created database connection object, which we
call database access object here. The reason is since the database
access object is shared among all the JSP pages and Servlets in a single
Web application, it should be initialized when the application gets
started, instead of in each JSP page. Java Servlet technology provides
application life-cycle event and listener classes for this purpose.
(Please see how the database.BookDBAO has been set in <jwsdpinstall>\tutorial\examples\web\bookstore2\src\listeners\ContextListene
r.java.)

31

05/04/2007

Steps for Developing


JSP-based Web
Application
32

Now let's go over the steps you will follow to develop JSP-based web
application.

32

05/04/2007

Web Application Development


and Deployment Steps
1.Write (and compile) the Web component code
(Servlet or JSP) and helper classes referenced
by the web component code
2.Create any static resources (for example, images
or HTML pages)
3.Create deployment descriptor (web.xml)
4.Build the Web application (*.war file or
deployment-ready directory)
5.Install or deploy the web application into a Web
container
?

Clients (Browsers) are now ready to access them via


URL

33

So this is the list of steps you will follow to develop and deploy a web application. By
the way, this is the same steps we talked during the WebApplication Architecture
session. I modified it a bit here so that the focus is given to JSP.
First, you will write and compile web component code, that is servlet Java code or JSP
pages and helper classes that are used by those web components. You also need to
create any static resources such as images or HTML pages.
Next, you will create deployment descriptor, that is, web.xml file. Then you will build
web application. As was mentioned, a web application can be either in the form of
WAR file or in the form of laid out directory structure of the WAR file.
Then you will install and deploy the web application to the web container. Once a web
application is deployed, then client can access the web resources through the HTML
browser. So let's go over each of these steps one by one.

33

05/04/2007

1. Write and compile the Web


component code
?
?

Create development tree structure


Write either servlet code and/or JSP pages
along with related helper code
Create build.xml for Ant-based build (and
other application life-cycle management)
process

34

So the first step is to write and compile web component codes. Now just like any other
application development, you might want to create development directory structure that
fits your need. As we will see in the following slide, people recommend a particular
directory structure they found suitable for web application development. And different
servlet container technologies use a bit different directory structures. We are using
Tomcat's example here.
Once you create an appropriate development directory structure, you can then write
servlet Java code or JSP pages along with related helper classes and other pieces. Now
another thing people find quite useful is to use ANT build tool for the development and
deployment tasks of web applications. ANT is platform independent make utility. And
the file that contains the build instruction is called build.xml file.

34

05/04/2007

Development Tree Structure


?

Keep Web application source separate from


compiled files

facilitate iterative development

Root directory

build.xml: Ant build file


context.xml: Optional application configuration file
src: Java source of servlets and JavaBeans
components
web: JSP pages and HTML pages, images

35

To facilitate iterative development and keep Web application source separate from
compiled files, the source code for the tutorial examples is stored in the following
structure under each application directory, for example, hello1.
build.xml - Ant build file
context.xml - Optional application configuration file
? src directory - Java source of servlets and JavaBeans components
? web directory - JSP pages and HTML pages, images
?
?

The Ant build file (build.xml) distributed with the examples contain targets to create an
unpacked WAR structure in the build subdirectory of mywebapp, copy and compile
files into that directory, and invoke the manager commands via special Ant tasks to
install, reload, remove, deploy, and undeploy applications.

35

05/04/2007

Example: Hello1 Example Tree Structure


(before ant build command)
?

hello1 directory (from Java EE 1.4 tutorial)


web directory
? duke.waving.gif
? index.jsp
? response.jsp
? WEB-INF directory

web.xml
build.xml
(it does not have src directory since this does not
use any Java classes as utility classes)
36

So this is an example directory structure of hello1 web application you find in the Java
WSDP. There are two servlet Java source files. And there is a web directory called web
which contains WEB-INF directory and other static resource files.

36

05/04/2007

2. Create any static resources


?

HTML pages

Custom pages
Login pages
Error pages

Image files that are used by HTML pages or


JSP pages

Example: duke.waving.gif

37

The next step is to create any static resources that will be used by the web components.
And they include some static HTML pages or image files. And an example of image is
duke that you see quite often in various Java-related web pages.

37

05/04/2007

3. Create deployment
descriptor (web.xml)
?

Deployment descriptor contains deployment


time runtime instructions to the Web
container

URN that the client uses to access the web


component

Every web application has to have it

38

The next step is to create deployment descriptor, web.xml file. By the way, the name of
this file has to be web.xml file.
The web.xml file contains deployment time and runtime instructions to the web
container. For example, you can specify the URN that clients of your web applications
will use to access your web components. Every web application has to have a web.xml
file.

38

05/04/2007

web.xml for Hello1


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
<display-name>Hello2</display-name>
<description>no description</description>
<servlet>
<servlet-name>greeting</servlet-name>
<display-name>greeting</display-name>
<description>no description</description>
<jsp-file>/greeting.jsp</jsp-file>
<!-- what gets called -->
</servlet>
<servlet-mapping>
<servlet-name>greeting</servlet-name>
<url-pattern>/greeting</url-pattern> <!-- URL from browser ->
</servlet-mapping>
</web-app>
39

For JSP web component, the sub element that needs to be specified under <servlet>
element is <jsp-file> instead of <servlet-class> element.
Now here in hello2 example, you can see that instead of specifying a servlet class with
<servlet-class> element, the web.xml file specifies the JSP file with <jsp-file>. For
example, the web.xml file of the Hello1 servlet, there is a following line
<servlet-class>GreetingServlet</servlet-class>
In web.xml for JSP page, we have the following line instead.
<jsp-file>/greeting.jsp</jsp-file>

39

05/04/2007

4. Build the Web application


?

Either *.WAR file or unpacked form of *.WAR


file
Build process is made of

create build directory (if it is not present) and its


subdirectories
copy *.jsp files under build directory
compile Java code into build/WEB-INF/classes
directory
copy web.xml file into build/WEB-INF directory
copy image files into build directory
40

Once you have all the pieces, you can create a web application. As mentioned before, a
web application is basically a deployable package that contains everything that is
needed for the deployment.
A web application is either in the form of *.war file or unpacked or laid out form of the
*.war file. Typically the build process of the web application involves creating build
directory which is the root directory for the compile time generated pieces such as Java
classes and pieces that are needed to create *.war file such as web.xml file. For
example, the compiled java classes will end up residing in build/WEB-INF/classes
directory and web.xml file is also copied to build/WEB-INF directory and the image
files are copied into the build directory itself. Basically the build directory is the
reflection of directory structure that a particular web container expects.

40

05/04/2007

Example: Hello2 Tree Structure


(after ant build command)
?

Hello2
web directory
build.xml
build directory
? WEB-INF directory
classes directory
web.xml
? duke.waving.gif
? greeting.jsp
? response.jsp
41

So this is the example directory structure of hello1 web application. Once the build
process is completed via ant build command, the build directory gets created if it is
not present yet, and greetingservlet and responseservlet classes are created in classes
subdirectory and web.xml file is copied from web directory to build/WEB-INF directory
and image file is copied from web directory to build/ directory. Now the build directory
is now ready to be taken either as a source directory for creating *.war file or can be
copied over to web container for deployment.

41

05/04/2007

5. Install or Deploy Web application


?

There are 2 different ways to install/deploy


Web application

By asking Tomcat Manager via sending a command


to it (Tomcat Manager is just another Servlet app
that is always running)
?
?

ant install
ant deploy

By manually copying files to Tomcat's webapps


directory and then restarting Tomcat
42

Once you built a ready to deployable web application, you can now deploy the
application over the web container.
Now for Tomcat, there are two different ways you can install/deploy your web
applications. The first method is by sending a request to Tomcat manager and the other
method is a bit of brute force method which is you manually copy the *.war file or
directory structure to the webapps directory of Tomcat and then restart.
Now let's talk about a bit on the first method. Basically what is happening underneath
when you invoke ant install or ant deploy command is that you are running Java
application in which HTTP request message that contains the information about your
web application such as name and location of it gets constructed and sent to Tomcat
manager which itself is a servlet application.

42

05/04/2007

5.1 Install or Deploy Web application


?

Via Tomcat manager

You need proper credential to perform this


?

This is why you need build.properties file with proper


userid and password, otherwise you will experience
HTTP 401 error

ant install for temporary deployment


ant deploy for permanent deployment

Manual Method

Copying *.war file or unpacked directory to <tomcatinstall>/webapps/ directory manually and then
restart Tomcat
43

Now when you are asking Tomcat manager to install or deploy your web application,
basically what you are asking is to change a setting on the server side which should be
privileged operations. What that means is that you need to provider proper credentials
along with your installation and deployment requests. This is why you need
build.properties file with proper user id and password. Otherwise, you will experience
HTTP 401 error condition, which basically says that an access controlled web resource,
in this case, the Tomcat manager, is being accessed with invalid userid and password.
Now let's talk about the difference between installation and deployment. Installation
under Tomcat's context is a temporary installation while deployment is a permanent
deployment. So when Tomcat gets restarted, an installed web application is not going
to be run again while a deployed application will be started automatically by the
container.
Again the manual method is basically coping the *.war file or whole directory structure
to Tomcat's webapps directory and in this method.

43

05/04/2007

6. Perform Client Access to Web


Application
?

From a browser, go to URN of the Web


application

http://localhost:8080/hello2/greeting

44

Once your web application is deployed, then you can try to access the web components
via your browser by specifying the appropriate URN address.

44

05/04/2007

http://localhost:8080/hello2/greeting

45

So for the hello1 example web application, a client will specify


http://localhost:8080/hello2/greeting to access the web resource.

45

05/04/2007

response.jsp

46

This is response html page that gets displayed as a result of the handling of the first
HTTP request that comes from the client.

46

05/04/2007

Comparing
Hello1 Servlet &
Hello2 JSP code
47

Now let's compare Hello world programs written in Servlet and JSP and see
how they match up against each other.

47

05/04/2007

GreetingServlet.java (1)
import
import
import
import
import

java.io.*;
java.util.*;
java.sql.*;
javax.servlet.*;
javax.servlet.http.*;

/**
* This is a simple example of an HTTP Servlet. It responds to the GET
* method of the HTTP protocol.
*/
public class GreetingServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();
// then write the data of the response
out.println("<html>" +
"<head><title>Hello</title></head>");

48

So this is code listing of GreetingServlet in Hello1 example under Java WSDP. This is
the first part of 3 pages of the code.
What happens in this code is pretty simple. It basically receives a HTTP request, then
create output stream object and write HTTP response to the output stream.

48

05/04/2007

GreetingServlet.java (2)
// then write the data of the response
out.println("<body bgcolor=\"#ffffff\">" +
"<img src=\"duke.waving.gif\">" +
"<h2>Hello, my name is Duke. What's yours?</h2>" +
"<form method=\"get\">" +
"<input type=\"text\" name=\"username\" size=\"25\">" +
"<p></p>" +
"<input type=\"submit\" value=\"Submit\">" +
"<input type=\"reset\" value=\"Reset\">" +
"</form>");
String username = request.getParameter("username");
// dispatch to another web resource
if ( username != null && username.length() > 0 ) {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/response");
if (dispatcher != null)
dispatcher.include(request, response);
}
out.println("</body></html>");
out.close();
}

49

This is the continuation of writing to the output stream. Then it dispatches to another
web resource called /response.

49

05/04/2007

GreetingServlet.java (3)
public String getServletInfo() {
return "The Hello servlet says hello.";
}
}

50

50

05/04/2007

greeting.jsp
<html>
<head><title>Hello</title></head>
<body bgcolor="white">
<img src="duke.waving.gif">
<h2>My name is Duke. What is yours?</h2>
<form method="get">
<input type="text" name="username" size="25">
<p></p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
%>
<%@include file="response.jsp" %>
<%
}
%>
</body>
</html>

51

Now this is the Hello web application this time using JSP. As you can see, JSP includes
HTML tags so you are not creating HTML response in your Java code, instead they are
part of JSP page. Then some dynamic contents are created through embedded Java
code within the JSP page.
By the way, as we will see later on, inserting Java code as part of JSP page is not really
a recommended way of performing dynamic contents generation. I am just showing this
example to make a point.

51

05/04/2007

ResponseServlet.java
import
import
import
import
import

java.io.*;
java.util.*;
java.sql.*;
javax.servlet.*;
javax.servlet.http.*;

// This is a simple example of an HTTP Servlet. It responds to the GET


// method of the HTTP protocol.
public class ResponseServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
PrintWriter out = response.getWriter();
// then write the data of the response
String username = request.getParameter("username");
if ( username != null && username.length() > 0 )
out.println("<h2>Hello, " + username + "!</h2>");
}
public String getServletInfo() {
return "The Response servlet says hello.";
}
}

52

This is the web component, ResponseServlet, that was dispatched from the
GreetingServlet.

52

05/04/2007

response.jsp
<h2><font color="black">Hello, <%=username%>!</font></h2>

53

This the corresponding JSP page. As you can see, as far as displaying is concerned, JSP
is a much simpler to use.

53

05/04/2007

JSP is Servlet!
54

Now I want you to understand that JSP and servlet are very closely related. I
would even claim that JSP pages are servlets. What happens underneath is that
JSP pages are translated and compiled into corresponding servlet code and
classes transparently.
In a sense, JSP provides separation of contents generation from presentation
logic while maintaining all the benefits that come with servlet.

54

05/04/2007

JSP is Servlet
?

JSP pages get translated into servlet

Tomcat translates greeting.jsp into greeting$jsp.java

Scriptlet (Java code) within JSP page ends


up being inserted into jspService() method of
resulting servlet
Implicit objects for servlet are also available
to JSP page designers, JavaBeans
developers, custom tag designers

55

Just to reiterate how JSP and Servlet are closely related, I would say that JSP is in fact
Servlet.
First JSP pages get translated into servlet class when they get deployed. Second, the
scriptlet which is Java code within JSP page ends up being directly inserted into the
jspService() method of the resulting servlet class without any modification. Third, the
implicit objects that are available to servlet programmers such as HttpSession object,
ServletContext objects are also available to JSP page designers, JavaBeans developers,
custom tag designers.

55

05/04/2007

greeting$jsp.java (1)
package org.apache.jsp;
import
import
import
import

javax.servlet.*;
javax.servlet.http.*;
javax.servlet.jsp.*;
org.apache.jasper.runtime.*;

public class greeting$jsp extends HttpJspBase {

static {
}
public greeting$jsp( ) {
}
private static boolean _jspx_inited = false;
public final void _jspx_init() throws
org.apache.jasper.runtime.JspException {
}

56

So this is the greeting.jsp's corresponding servlet class that was created by the
container.

56

05/04/2007

greeting$jsp.java (2)
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;

57

This is continuation of translated code. Please note that there are variables that contain
the references to servlet related objects such as pageContext object, HttpSession object,
ServletContext object, ServletConfig object and output stream object.

57

05/04/2007

greeting$jsp.java (3)
try {
if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request,
response,"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
58

And in this code, those variables are initialized.

58

05/04/2007

greeting$jsp.java (4)
// HTML // begin [file="/greeting.jsp";from=(38,4);to=(53,0)]
out.write("\n\n<html>\n<head><title>Hello</title></head>\n<body
bgcolor=\"white\">\n<img src=\"duke.waving.gif\"> \n<h2>My name is Duke.
What is yours?</h2>\n\n<form method=\"get\">\n<input type=\"text\"
name=\"username\" size=\"25\">\n<p></p>\n<input type=\"submit\"
value=\"Submit\">\n<input type=\"reset\"
value=\"Reset\">\n</form>\n\n");
// end
// begin [file="/greeting.jsp";from=(53,2);to=(56,0)]
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
// end
// HTML // begin [file="/greeting.jsp";from=(56,2);to=(57,4)]
out.write("\n
");
// end
// HTML // begin [file="/response.jsp";from=(38,4);to=(40,31)]
out.write("\n\n<h2><font color=\"black\">Hello, ");
// end
// begin [file="/response.jsp";from=(40,34);to=(40,42)]
out.print(username);

59

This code deals with generating HTML pages.

59

05/04/2007

greeting$jsp.java (5)
// HTML // begin [file="/response.jsp";from=(40,44);to=(55,0)]
out.write("!</font></h2>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
// end
// HTML // begin [file="/greeting.jsp";from=(57,37);to=(58,0)]
out.write("\n");
// end
// begin [file="/greeting.jsp";from=(58,2);to=(60,0)]
}
// end
// HTML // begin [file="/greeting.jsp";from=(60,2);to=(63,0)]
out.write("\n</body>\n</html>\n");
// end
} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0) out.clearBuffer();
if (pageContext != null) pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(pageContext);
}
}
}

60

This is the continuation of code that deals with generation of HTML page. As you can
see, all the dirty work of generating HTML page is done by the compiler.

60

05/04/2007

Dynamic Content
Generation
Techniques
in JSP

61

OK, by now I hope you got the sense on what the dynamic contents is and how
it is generated. Now let's talk about the dynamic contents generation
techniques in a bit more detail.

61

05/04/2007

Dynamic Contents Generation


Techniques with JSP Technology
?

Various techniques can be chosen


depending on the following factors

size and complexity of the project


Requirements on re usability of code,
maintainability, degree of robustness

Simple to incrementally complex


techniques are available

62

There are several dynamic contents generation techniques you can


use. And you choose these techniques depending on the size and
complexity of your project. And these techniques provide different
levels of code reusability, maintenability, and robustness.

62

05/04/2007

Dynamic Contents Generation


Techniques with JSP
a) Call Java code directly within JSP
b) Call Java code indirectly within JSP
c) Use JavaBeans within JSP
d) Develop and use your own custom tags
e) Leverage 3rd-party custom tags or JSTL
(JSP Standard Tag Library)
f) Follow MVC design pattern
g) Leverage proven Model2 frameworks
63

This slide lists dynamic contents generation techniques that can be used with
JSP in the order of its sophistication, from the least sophisticated to the most
sophisticated. So let's talk about these in a bit more detail.

63

05/04/2007

(a) Call Java code directly


?
?

Place all Java code in JSP page


Suitable only for a very simple Web
application

hard to maintain
hard to reuse code
hard to understand for web page authors

Not recommended for relatively


sophisticated Web applications

weak separation between contents and


presentation

64

The least sophisticated method is to place all the Java code within a
JSP page. Because, in this method, the business logic which is
represented in Java code and presentation logic which is represented
in JSP pages are intermixed, it provides somewhat weak separation
between the two, which means it is rather hard to maintain and reuse
the code. And web page authors will have difficult time to
understand the JSP page. So this design model provides only a
slightly better separation between contents and presentation logic
than servlet only code.

64

05/04/2007

(b) Call Java code indirectly


?
?

Develop separate utility classes


Insert into JSP page only the Java code
needed to invoke the utility classes
Better separation of contents generation
from presentation logic than the previous
method
Better re usability and maintainability than
the previous method
Still weak separation between contents and
presentation, however

65

Now the next level of sophistication can be achieved by developing


utility classes and then insert only the Java code need to invoke
those utility classes while maintaining those utility class outside of
the JSP page.
This will result in a better separation of contents generation from
presentation logic and better reusability and maintenability than
method (a) of previous slide. But since the code is not in the form
of components yet, the separation is still considered weak.

65

05/04/2007

(c) Use JavaBeans


?

Develop utility classes in the form of


JavaBeans
Leverage built-in JSP facility of creating
JavaBeans instances, getting and setting
JavaBeans properties

?
?

Use JSP element syntax

Easier to use for web page authors


Better re usability and maintainability than
the previous method
66

Now in the next level, you can develop those utility classes in the
form of simple component, JavaBeans in this case.
Using JavaBeans within a JSP page has an advantage over method
(a) and (b) because there is a built-in support of getting and setting
JavaBeans properties in JSP architecture as we will see later on.
And because of this built-in support, accessing JavaBeans from JSP
page is a lot easier thing to do for web page authors again compared
to method (a) and (b).
And because the logic of contents generations is captured in a
component form of JavaBeans, the reusability and maintenability
increases.

66

05/04/2007

(d) Develop and Use Custom Tags


?

Develop sophisticated components called


custom tags

More powerful than JavaBeans component

?
?

Custom tags are specifically designed for JSP


More than just getter and setter methods

re usability, maintainability, robustness


Development of custom tags are more
difficult than creating JavaBeans, however
67

The next level is building contents generation or business


logic in the form of more sophisticated components, which
are called custom tags. Custom tags are component forms
that are specifically designed for JSP. And it is more
powerful than JavaBeans as a component model, thus
provides better reusability, maintenability, and robustness.

67

05/04/2007

(e) Use 3rd-party Custom tags or


JSTL
?

There are many open source and


commercial custom tags available

Apache Struts

JSTL (JSP Standard Tag Library)


standardize the set of custom tags that
should be available over Java EE platform
at a minimum

As a developer or deployer, you can be assured


that a standard set of custom tags are already
present in Java EE compliant platform (J2EE 1.3
and after)

68

Now one significant value of using custom tags in your design of


JSP pages is that you can use 3rd-party custom tags. And in fact,
there are many 3rd-party custom tags available including open
source community.
Another big advantage is that the JSP community also agree on
standard set of custom tags that should be available on all J2EE
compliant platforms, which means you don't have to be concerned
about availability of these custom tags on J2EE platform.

68

05/04/2007

(f) Design/Use MVC Design Pattern


?

Follow MVC design pattern

Model using some model technologies


View using JSP
Controller using Servlet

Creating and maintaining your own MVC


framework is highly discourage, however

69

The most sophisticated design involves the usage of MVC-pattern


based web application frameworks. And examples of these
frameworks include Apache Struts and JavaServer Faces.

69

05/04/2007

(g) Use Proven MVC Model2


Frameworks
?

There are many to choose from

Apache Struts
JavaServer Faces (JSF)
Other frameworks: Echo, Tapestry, WebWorks,
Wicket

70

The most sophisticated design involves the usage of MVC-pattern


based web application frameworks. And examples of these
frameworks include Apache Struts and JavaServer Faces.

70

05/04/2007

Invoking Java Code


with JSP Scripting
Elements
71

Now let's talk about how to use Java code within JSP page using JSP scripting
elements. Using JSP scripting elements addresses the dynamic contents
generation techniques (a) and (b).

71

05/04/2007

JSP Scripting Elements


?

Lets you insert Java code into the servlet that


will be generated from JSP page
Minimize the usage of JSP scripting elements
in your JSP pages if possible
There are three forms

Expressions: <%= Expressions %>


Scriptlets: <% Code %>
Declarations: <%! Declarations %>

72

Scripting elements let you insert raw Java code into the JSP page directly
and this code will be in turn inserted into the Servlet code that will be
generated from the JSP page.
As was mentioned, the best practice recommendation is not to use scripting
elements if possible.
Scripting elements can be in 3 different forms - expression, scriptlets, and
declarations and they use different syntax as shown in the slide.

72

05/04/2007

Expressions
?

During execution phase

Expression is evaluated and converted into a String


The String is then Inserted into the servlet's output
stream directly
Results in something like out.println(expression)
Can use predefined variables (implicit objects)
within expression

Format
<%= Expression %> or
<jsp:expression>Expression</jsp:expression>
Semi-colons are not allowed for expressions
73

A JSP expression is used to insert the value of a scripting language


expression, converted into a string, into the data stream returned to the
client. When the scripting language is the Java programming language,
an expression is transformed into a statement that converts the value of
the expression into a String object and inserts it into the implicit out
object. So the end result is like out.println(expression) if you've done it
in servlet yourself.
The syntax for an expression is as follows. The first is JSP 1.1 syntax and
the 2 nd one is introduced in JSP 1.2.
<%= expression %>
<jsp:expression> expression </jsp:expression>
Note that a semicolon is not allowed within a JSP expression, even if the
same expression has a semicolon when you use it within a scriptlet.

73

05/04/2007

Example: Expressions
?

Display current time using Date class

Display random number using Math class

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


Random number: <%= Math.random() %>

Use implicit objects

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


Your parameter: <%= request.
getParameter(yourParameter) %>
Server: <%= application.getServerInfo() %>
Session ID: <%= session.getId() %>
74

These are the examples of expressions. For example, you can use
expression to display current time using Java Date class. Or you can
display the random number using Math class.
Or as was mentioned, you can access all implicit objects such as
HttpServletRequest, ServletContext object, and HttpSession objects.
Because JSP already defined the names of these implicit objects, you
have to use predefined names in your JSP page. For example
HttpServletRequest object is represented by request, ServletContext
object by application, HttpSession object by session.

74

05/04/2007

Scriptlets
?

Used to insert arbitrary Java code into


servlet's jspService() method
Can do things expressions alone cannot do

setting response headers and status codes


writing to a server log
updating database
executing code that contains loops, conditionals

Can use predefined variables (implicit


objects)
Format:

<% Java code %> or


<jsp:scriptlet> Java code</jsp:scriptlet>

75

A JSP scriptlet is used to contain any code fragment that is valid for the
scripting language used in a page. The syntax for a scriptlet is as follows:
<%
scripting language statements
%>
When the scripting language is set to Java programming language, a
scriptlet is transformed into a Java programming language statement
fragment and is inserted into the service() method of the JSP page's servlet.
A programming language variable created within a scriptlet is accessible
from anywhere within the JSP page.

75

05/04/2007

Example: Scriptlets
?

Display query string


<%
String queryData = request.getQueryString();
out.println(Attached GET data: + queryData);
%>

Settng response type


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

76

This is an example scriptlets. The first example fills the output stream
with some query data while in the 2 nd example, response type is set
through HttpServletResponse implicit object.

76

05/04/2007

Example: Scriptlet with Loop


<%
Iterator i = cart.getItems().iterator();
while (i.hasNext()) {
ShoppingCartItem item =
(ShoppingCartItem)i.next();
BookDetails bd = (BookDetails)item.getItem();
%>
<tr>
<td align="right" bgcolor="#ffffff">
<%=item.getQuantity()%>
</td>
<td bgcolor="#ffffaa">
<strong><a href="
<%=request.getContextPath()%>/bookdetails?bookId=
<%=bd.getBookId()%>"><%=bd.getTitle()%></a></strong>
</td>
...
<%
// End of while
}
%>

77

The JSP page showcart.jsp contains a scriptlet that retrieves an iterator


from the collection of items maintained by a shopping cart and sets up a
construct to loop through all the items in the cart. Inside the loop, the JSP
page extracts properties of the book objects and formats them using HTML
markup. Since the while loop opens a block, the HTML markup is
followed by a scriptlet that closes the block.

77

05/04/2007

Example: Scriptlet Result

78

And this is the output.

78

05/04/2007

Example: JSP page fragment


?

Suppose we have the following JSP page


fragment

<H2> sangHTML </H2>


<%= sangExpression() %>
<% sangScriptletCode(); %>

79

Now I know we dealt with several JSP elements. And let's see these
different JSP elements are in fact translated into corresponding Java
code.
Now let's say that we have the JSP page fragment that contains 3
different JSP elements mentioned in this slide. And let's see how these 3
JSP elements are translated into Java code in the following slide.

79

05/04/2007

Example: Resulting Servlet Code


public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
HttpSession session = request.getSession(true);
JSPWriter out = response.getWriter();
// Static HTML fragment is sent to output stream in as is form
out.println(<H2>sangHTML</H2>);
// Expression is converted into String and then sent to output
out.println(sangExpression());
// Scriptlet is inserted as Java code within _jspService()
sangScriptletCode();
...

80

So static HTML fragment is sent to the output stream in as it is form.


The expression is converted into String and then sent to the output
stream.
The scriptlet is directly inserted as raw Java code within _jspService()
method.

80

05/04/2007

Declarations
?

Used to define variables or methods that get


inserted into the main body of servlet class

?
?

Outside of _jspSevice() method


Implicit objects are not accessible to declarations

Usually used with Expressions or Scriptlets


For initialization and cleanup in JSP pages, use
declarations to override jspInit() and jspDestroy()
methods
Format:

<%! method or variable declaration code %>


<jsp:declaration> method or variable declaration
code </jsp:declaration>

81

Now let's talk about declarations a bit. Declaration is used to to define


variables or methods that get inserted into the main body of the resulting
servlet class. Please note that these are inserted outside of _jspService()
method. So implicit objects such as HttpSession object are not accessible
to declarations.
Declarations are usually used with expressions or scriptlets.
One usage of declaration is for initialization and cleanup in a JSP page. So
you can use declarations to override jspInit() or jspDestroy() methods.
The format of declarations are shown in the slide, the first format is
supported in both JSP 1.1 and 1.2 while the 2 nd format is supported only in
JSP 1.2.

81

05/04/2007

Example: JSP Page fragment


<H1>Some heading</H1>
<%!
private String randomHeading() {
return(<H2> + Math.random() + </H2>);
}
%>
<%= randomHeading() %>

82

So in this slide, we have a method declaration example. The declaration of


the method called randomHeading() and the usage of it within an
expression.

82

05/04/2007

Example: Resulting Servlet Code


public class xxxx implements HttpJSPPage {
private String randomHeading() {
return(<H2> + Math.random() + </H2>);
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
HttpSession session = request.getSession(true);
JSPWriter out = response.getWriter();
out.println(<H1>Some heading</H1>);
out.println(randomHeading());
...
}
...
}

83

And this is the resulting Servlet code. Please note that method declaration
reside outside of _jspService() method. And usage of the declared method
within in expression inside the _jspService() method.

83

05/04/2007

Example: Declaration
<%!
private BookDBAO bookDBAO;
public void jspInit() {
...
}
public void jspDestroy() {
...
}
%>

84

This slide shows how you can override jspInit() and jspDestroy() using
declaration.

84

05/04/2007

Why XML Syntax?


?
?

From JSP 1.2


Examples

<jsp:expression>Expression</jsp:expression>
<jsp:scriptlet> Java code</jsp:scriptlet>
<jsp:declaration> declaration code
</jsp:declaration>

You can leverage

XML validation (via XML schema)


Many other XML tools
? editor
? transformer
? Java APIs
85

Now as shown several times, there are two different syntax or format for
JSP elements, one that is being supported from JSP 1.1 and the other,
which is compliant with XML syntax, is supported from JSP 1.2.
Using XML syntax for JSP element has several advantages. For
example, you can use XML validation and many XML tools out there.

85

05/04/2007

Including and
Forwarding to Other
Web Resource
86

86

05/04/2007

Including Contents in a JSP Page


?

Two mechanisms for including another Web


resource in a JSP page

include directive
jsp:include element

87

There are two mechanisms for including another Web resource in a JSP
page: the include directive and the jsp:include element.

87

05/04/2007

Include Directive
?

Is processed when the JSP page is


translated into a servlet class
Effect of the directive is to insert the text
contained in another file-- either static
content or another JSP page--in the
including JSP page
Used to include banner content, copyright
information, or any chunk of content that you
might want to reuse in another page
Syntax and Example

<%@ include file="filename" %>


<%@ include file="banner.jsp" %>

88

The include directive is processed when the JSP page is translated into a
servlet class. The effect of the directive is to insert the text contained in
another file-- either static content or another JSP page--in the including
JSP page. You would probably use the include directive to include
banner content, copyright information, or any chunk of content that you
might want to reuse in another page. The syntax for the include directive
is as follows:
<%@ include file="filename" %>
For example, all the bookstore application pages include the file
banner.jsp which contains the banner content, with the following
directive:
<%@ include file="banner.jsp" %>

88

05/04/2007

jsp:include Element
?
?

Is processed when a JSP page is executed


Allows you to include either a static or
dynamic resource in a JSP file

static: its content is inserted into the calling JSP file


dynamic: the request is sent to the included
resource, the included page is executed, and then
the result is included in the response from the
calling JSP page

Syntax and example

<jsp:include page="includedPage" />


<jsp:include page="date.jsp"/>
89

The jsp:include element is processed when a JSP page is executed. The


include action allows you to include either a static or dynamic resource in
a JSP file. The results of including static and dynamic resources are quite
different. If the resource is static, its content is inserted into the calling
JSP file. If the resource is dynamic, the request is sent to the included
resource, the included page is executed, and then the result is included in
the response from the calling JSP page. The syntax for the jsp:include
element is:
<jsp:include page="includedPage" />
The date application introduced at the beginning of this chapter includes
the page that generates the display of the localized date with the
following statement:
<jsp:include page="date.jsp"/>

89

05/04/2007

Which One to Use it?


?

Use include directive if the file changes


rarely
It is faster than jsp:include
Use jsp:include for content that changes
often
Use jsp:include if which page to include
cannot be decided until the main page is
requested

90

So when do you want use Include directive and when do you want to use
include element.
The best practice guideline recommends that you use include directive if
the included JSP page changes rarely because directive processing is
faster than the processing of include element.
And use include element when the contents changes often or if the page
to include cannot be decided until the main page is requested.

90

05/04/2007

Forwarding to another Web


component
?
?

Same mechanism as in Servlet


Syntax

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

Original request object is provided to the


target page via jsp:parameter element
<jsp:forward page="..." >
<jsp:param name="param1" value="value1"/>
</jsp:forward>
91

The mechanism for transferring control to another Web component from


a JSP page uses the functionality provided by the Java Servlet API as
described in Transferring Control to Another Web Component. You
access this functionality from a JSP page with the jsp:forward element:
<jsp:forward page="/main.jsp" />
When an include or forward element is invoked, the original request
object is provided to the target page. If you wish to provide additional
data to that page, you can append parameters to the request object with
the jsp:param element:
<jsp:forward page="..." >
<jsp:param name="param1" value="value1"/>
</jsp:forward>

91

05/04/2007

Directives
92

92

05/04/2007

Directives
?

Directives are messages to the JSP


container in order to affect overall structure
of the servlet
Do not produce output into the current
output stream
Syntax
<%@ directive {attr=value}* %>

93

OK, let's talk about directive. Directives are messages (or instruction) to
the JSP container. And directives do not produce any output. And the
syntax is as shown in the slide.

93

05/04/2007

Three Types of Directives


?

page: Communicate page dependent


attributes and communicate these to the JSP
container
<%@ page import="java.util.* %>

include: Used to include text and/or code at


JSP page translation-time
<%@ include file="header.html" %>

Taglib: Indicates a tag library that the JSP


container should interpret
<%@ taglib uri="mytags" prefix="codecamp" %>
94

There are three types of directives. page directive, include directive, and
TagLib directive. The page directive is used to communicate page
dependent attributes to the JSP container for example importing Java
classes.
The include directive is used to include text or code at JSP translation time,
for example including a HTML page.
The TagLib directive indicates a tag library that the JSP container should
interpret.

94

05/04/2007

Page Directives
?

Give high-level information about the


servlet that results from the JSP page.
Control
Which classes are imported
<%@ page import="java.util.* %>
What MIME type is generated
<%@ page contentType="MIME-Type" %>
How multithreading is handled
<%@ page isThreadSafe="true" %> <%!--Default -%>
<%@ page isThreadSafe="false" %>
What page handles unexpected errors
<%@ page errorPage="errorpage.jsp" %>

95

This slide shows the examples of page directives. For example, you can
use directory to specify which Java classes should be imported, what mime
types should be generated, how multithreading is handled, and which page
handles errors and so on.

95

05/04/2007

Implicit Objects
?

?
?

A JSP page has access to certain implicit


objects that are always available, without
being declared first
Created by container
Corresponds to classes defined in Servlet

96

Implicit objects are created by the Web container transparently and


contain information related to a particular request, page, or application.
Many of the objects are defined by the Java Servlet technology.

96

05/04/2007

Implicit Objects
?
?
?
?
?
?
?

request (HttpServletRequest)
response (HttpServletRepsonse)
session (HttpSession)
application(ServletContext)
out (of type JspWriter)
config (ServletConfig)
pageContext

97

The request object is subtype of javax.servlet.ServletRequest.

97

05/04/2007

Scope Objects
98

98

05/04/2007

Different Scope

99

The scope objects that are defined under servlet are also available to JSP
page designers, bean developers, custom tag developers. Scope objects are
used to maintain object-value pairs that can be shared within a particular
scope.
There are four scope objects whose scope are different. On the top, we
have application scope object, whose scope is web application. A single
web application can be made of multiple web components, that is, multiple
servlets and JSP pages. And any object-value pairs that are maintained in
application scope are shared among the servlets and JSP within that
application.
Session scope object maintains object-value pairs that can be shared within
the session.

99

05/04/2007

Session, Application Scope


Client 1

server

Session 1

Session ID 1

Client 2

Session ID 2

Session 2

Client 1

server

application
Client 2

100

This picture shows the difference of scope between session and


application. A session is owned by a particular client while application
scope which is represented by ServletContext object is shared by all clients
who access the same application.

100

05/04/2007

Session, Request, Page Scope


client

request

Page 1

forward

Page scope

response

request

Page 2

Page 3

Page scope

response

Page scope

request scope

Page 4

forward

Page scope

request scope

Session scope

101

So this picture shows relationship between session, request, and page


scopes. Page scope is per page. Request scope spans all the pages that are
involved in handling a particular request and session scope includes all the
request and responses in a single client specific session.

101

05/04/2007

JavaBeans Components
for JSP

102

Now let's talk about how JavaBeans components can be used within JSP
page.

102

05/04/2007

What are JavaBeans?


?

Java classes that can be easily reused


and composed together into an application
Any Java class that follows certain design
conventions can be a JavaBeans
component

properties of the class


public methods to get and set properties

Within a JSP page, you can create and


initialize beans and get and set the values
of their properties
JavaBeans can contain business logic or
data base access logic

103

JavaBeans components are Java classes that can be easily reused and
composed together into applications.
Any Java class that follows certain design conventions can be a
JavaBeans component. JavaBeans component design conventions
govern the properties of the class and govern the public methods that
give access to the properties.
JavaServer Pages technology directly supports using JavaBeans
components with JSP language elements. You can easily create and
initialize beans and get and set the values of their properties
And JavaBeans can contain business logic or database access logic.

103

05/04/2007

JavaBeans Design Conventions


?

JavaBeans maintain internal properties

A property can be

Properties should be accessed and set via


getXxx and setXxx methods

Read/write, read-only, or write-only


Simple or indexed

PropertyClass getProperty() { ... }


PropertyClass setProperty() { ... }

JavaBeans must have a zero-argument


(empty) constructor
104

A JavaBeans component property can be


* Read/write, read-only, or write-only
* Simple, which means it contains a single value, or indexed, which means it
represents an array of values
There is no requirement that a property be implemented by an instance
variable; the property must simply be accessible using public methods that
conform to certain conventions:
* For each readable property, the bean must have a method of the form
PropertyClass getProperty() { ... }
* For each writable property, the bean must have a method of the form
setProperty(PropertyClass pc) { ... }
In addition to the property methods, a JavaBeans component must define a
constructor that takes no parameters. If there are no other constructors, no arg
constructor is automatically generated.

104

05/04/2007

Example: JavaBeans
public class Currency {
private Locale locale;
private double amount;
public Currency() {
locale = null;
amount = 0.0;
}
public void setLocale(Locale l) {
locale = l;
}
public void setAmount(double a) {
amount = a;
}
public String getFormat() {
NumberFormat nf =
NumberFormat.getCurrencyInstance(locale);
return nf.format(amount);
}
}

105

In the BookStore application, the JSP pages catalog.jsp, showcart.jsp, and


cashier.jsp use the util.Currency JavaBeans component to format currency
in a locale-sensitive manner. The bean has two writable properties, locale
and amount, and one readable property, format.
The format property does not correspond to any instance variable, but
returns a function of the locale and amount properties.

105

05/04/2007

Why Use JavaBeans in JSP Page?


?

A JSP page can create and use any type of


Java programming language object within a
declaration or scriptlet like following:
<%
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
// If the user has no cart, create a new one
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
%>
106

Now do we care about JavaBeans in the context of JSP?


As was mentioned, a JSP page can create and use any type of Java
programming language object within a declaration or scriptlet. The
scriptlet above creates the bookstore shopping cart and stores it as a
session attribute.

106

05/04/2007

Why Use JavaBeans in JSP


Page?
?

JSP pages can use JSP elements to create


and access the object that conforms to
JavaBeans conventions
<jsp:useBean id="cart" class="cart.ShoppingCart"
scope="session"/>
Create an instance of ShoppingCart if none exists,
stores it as an attribute of the session scope object,
and makes the bean available throughout the
session by the identifier cart
107

If the shopping cart object in the precious page conforms to


JavaBeans conventions, JSP pages can use JSP elements to create
and access the object. For example, the Duke's Bookstore pages
bookdetails.jsp, catalog.jsp, and showcart.jsp replace the scriptlet
with the much more concise JSP useBean element:

107

05/04/2007

Compare the Two


<%
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
// If the user has no cart object as an attribute in Session scope
// object, then create a new one. Otherwise, use the existing
// instance.
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
%>
versus
<jsp:useBean id="cart" class="cart.ShoppingCart"
scope="session"/>

108

Now compare the two JSP codes. As you can tell JavaBeans based
JSP code is a lot more simpler and easy to understand and would be
easier to maintain. In other words, for web page authors, using
JavaBeans syntax is a lot easier than writing Java code.

108

05/04/2007

Why Use JavaBeans in JSP


Page?
?

?
?

No need to learn Java programming


language for page designers
Stronger separation between content and
presentation
Higher re usability of code
Simpler object sharing through built-in
sharing mechanism
Convenient matching between request
parameters and object properties
109

So just to summarize why you want to use JavaBeans over pure Java
code, there are several reasons.
First, page authors do not have to know Java programming language
in order to use JavaBeans in JSP page because usage syntax of
JavaBeans is very simple. Because content generation or business
logic is captured in the form of JavaBeans component, it provides a
stronger separation between content and presentation. And a single
JavaBean can be in fact reusable in other JSP pages.
JavaBeans also make it easier to share objects among multiple JSP
pages or between requests.
Finally JavaBeans greatly simplify the process of reading request
parameters, converting from strings, and stuffing the resuts inside
objects.

109

05/04/2007

Creating a JavaBeans
?

Declare that the page will use a bean that is


stored within and accessible from the
specified scope by jsp:useBean element
<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope"/>
or
<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope">
<jsp:setProperty .../>
</jsp:useBean>
110

You can declare that your JSP page will use a JavaBeans component
using either one of the two formats mentioned above. The second
format is used when you want to include jsp:setProperty statements for
initializing bean properties. So the 2 nd format is used only when a new
bean instance has to be created. If the bean instance already is present
as an attribute in the scope object, no setting occurs.
The jsp:useBean element declares that the page will use a bean that is
stored within and accessible from the specified scope, which can be
application, session, request, or page. If no such bean exists, the
statement creates the bean and stores it as an attribute of the scope
object.
The value of the id attribute determines the name of the bean in the
scope and the identifier used to reference the bean in other JSP elements
and scriptlets.

110

05/04/2007

Setting JavaBeans Properties


?
?

2 ways to set a property of a bean


Via scriptlet

<% beanName.setPropName(value); %>

Via JSP:setProperty

<jsp:setProperty name="beanName"
property="propName" value="string constant"/>
beanName must be the same as that specified for
the id attribute in a useBean element
There must be a setPropName method in the bean
111

There are two ways to set JavaBeans component properties in a JSP page:
with the jsp:setProperty element or with a scriptlet
<% beanName.setPropName(value); %>
Here beanName must be the same as that specified for the id attribute in a
useBean element. There must be a setPropName method in the JavaBeans
component. And paramName must be a request parameter name.
The syntax of the jsp:setProperty element depends on the source of the
property value. <jsp:setProperty name="beanName"
property="propName" value="string constant"/> is used when the source
is string constant. <jsp:setProperty name="beanName"
property="propName" param="paramName"/> is used when the source
is Request parameter.

111

05/04/2007

Setting JavaBeans Properties


?

jsp:setProperty syntax depends on the


source of the property

<jsp:setProperty name="beanName"
property="propName" value="string constant"/>
<jsp:setProperty name="beanName"
property="propName" param="paramName"/>
<jsp:setProperty name="beanName"
property="propName"/>
<jsp:setProperty name="beanName" property="*"/>
<jsp:setProperty name="beanName"
property="propName" value="<%= expression
%>"/>

112

The syntax of setting JavaBeans properties depends on the source of the


property.
(add more explanation here)

112

05/04/2007

Example: jsp:setProperty with Request


parameter
<jsp:setProperty name="bookDB" property="bookId"/>
is same as
<%
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
bookDB.setBookId(bookId);
...
%>
113

The Duke's Bookstore application demonstrates how to use the setProperty


element and a scriptlet to set the current book for the database helper bean.
For example, bookstore3/web/bookdetails.jsp uses the form:
<jsp:setProperty name="bookDB" property="bookId"/>
whereas bookstore2/web/bookdetails.jsp uses the form:
<% bookDB.setBookId(bookId); %>

113

05/04/2007

Example: jsp:setProperty with


Expression
<jsp:useBean id="currency" class="util.Currency"
scope="session">
<jsp:setProperty name="currency" property="locale"
value="<%= request.getLocale() %>"/>
</jsp:useBean>
<jsp:setProperty name="currency" property="amount"
value="<%=cart.getTotal()%>" />

114

The above fragments from the page bookstore3/web/showcart.jsp(of Java


WSDP) illustrate how to initialize a currency bean with a Locale object
and amount determined by evaluating request-time expressions. Because
the first initialization is nested in a useBean element, it is only executed
when the bean is created.

114

05/04/2007

Getting JavaBeans Properties


?

2 different ways to get a property of a bean

Convert the value of the property into a String and


insert the value into the current implicit out object
Retrieve the value of a property without converting it
to a String and inserting it into the out object

115

There are two ways to get JavaBeans component properties in a JSP page:
with the jsp:setProperty element or with a scriptlet

115

05/04/2007

Getting JavaBeans Properties & and


Convert into String and insert into out
?

2 ways
via scriptlet
?

via JSP:setProperty
?

<%= beanName.getPropName() %>


<jsp:getProperty name="beanName"
property="propName"/>

Requirements

beanName must be the same as that specified for


the id attribute in a useBean element
There must be a getPropName() method in a bean
116

There are several ways to retrieve JavaBeans component properties. Two


of the methods (the jsp:getProperty element and an expression) convert the
value of the property into a String and insert the value into the current
implicit out object:
* <jsp:getProperty name="beanName" property="propName"/>
* <%= beanName.getPropName() %>
For both methods, beanName must be the same as that specified for the id
attribute in a useBean element, and there must be a getPropName method
in the JavaBeans component.

116

05/04/2007

Getting JavaBeans Properties


without Converting it to String
?
?

Must use a scriptlet


Format
<% Object o = beanName.getPropName(); %>

Example
<%
// Print a summary of the shopping cart
int num = cart.getNumberOfItems();
if (num > 0) {
%>
117

If you need to retrieve the value of a property without converting it and


inserting it into the out object, you must use a scriptlet:
<% Object o = beanName.getPropName(); %>
Note the differences between the expression and the scriptlet; the
expression has an = after the opening % and does not terminate with a
semicolon, as does the scriptlet.

117

05/04/2007

Accessing Objects from JSP Page

118

The above picture summarizes where various types of objects are stored
and how those objects can be accessed from a JSP page.
Objects created by the jsp:useBean tag are stored as attributes of the scope
objects and can be accessed by jsp:[get|set]Property tags and in scriptlets
and expressions.
Objects created in declarations and scriptlets are stored as variables of the
JSP page's servlet class and can be accessed in scriptlets and expressions.

118

05/04/2007

Error Handling
119

119

05/04/2007

Creating An Exception Error Page


?
?

Determine the exception thrown


In each of your JSP, include the name of
the error page
<%@ page errorPage="errorpage.jsp" %>

Develop an error page, it should include


<%@ page isErrorPage="true" %>

In

the error page, use the exception


reference to display exception
information
<%= exception.toString() %>

120

Any number of exceptions can arise when a JSP page is executed. To


specify that the Web container should forward control to an error page if
an exception occurs, include the following page directive at the beginning
of your JSP page:
<%@ page errorPage="file_name" %>
The Duke's Bookstore application page initdestroy.jsp contains the
directive
<%@ page errorPage="errorpage.jsp"%>
The beginning of errorpage.jsp indicates that it is serving as an error page
with the following page directive:
<%@ page isErrorPage="true|false" %>
This directive makes the exception object (of type
javax.servlet.jsp.JspException) available to the error page, so that you can
retrieve, interpret, and possibly display information about the cause of the
exception in the error page.

120

05/04/2007

Example: initdestroy.jsp
<%@ page import="database.*" %>
<%@ page errorPage="errorpage.jsp" %>
<%!
private BookDBAO bookDBAO;
public void jspInit() {

// retrieve database access object, which was set once per web
application
bookDBAO =
(BookDBAO)getServletContext().getAttribute("bookDB");
if (bookDBAO == null)
System.out.println("Couldn't get database.");

public void jspDestroy() {


bookDBAO = null;
}
%>

121

This example code shows how to add error handling page as a page
directive.

121

05/04/2007

Example: errorpage.jsp
<%@ page isErrorPage="true" %>
<%@ page import="java.util.*" %>
<%
ResourceBundle messages =
(ResourceBundle)session.getAttribute("messages");
if (messages == null) {
Locale locale=null;
String language = request.getParameter("language");
if (language != null) {
if (language.equals("English")) {
locale=new Locale("en", "");
} else {
locale=new Locale("es", "");
}
} else
locale=new Locale("en", "");
messages = ResourceBundle.getBundle("BookStoreMessages", locale);
session.setAttribute("messages", messages);
}
%> ...

122

The beginning of errorpage.jsp indicates that it is serving as an error


page with the following page directive:
<%@ page isErrorPage="true|false" %>
This directive makes the exception object (of type
javax.servlet.jsp.JspException) available to the error page, so that you
can retrieve, interpret, and possibly display information about the
cause of the exception in the error page.

122

05/04/2007

Example: errorpage.jsp
... (continued)
<html>
<head>
<title><%=messages.getString("ServerError")%></title>
</head>
<body bgcolor="white">
<h3>
<%=messages.getString("ServerError")%>
</h3>
<p>
<%= exception.getMessage() %>
</body>
</html>

123

(to be added)

123

05/04/2007

Date Example

124

Let's take a look at Date example in Java WSDP.

124

05/04/2007

Date Example Output

125

The Web page above is a form that allows you to select a locale and
displays the date in a manner appropriate to the locale.

125

05/04/2007

Date Example
<%@ page import="java.util.*" %>
<%@ page import="MyLocales" %>
<%@ page contentType="text/html; charset=ISO-8859-5" %>
<html>
<head><title>Localized Dates</title></head>
<body bgcolor="white">
<jsp:useBean id="locales" scope="application" class="MyLocales"/>
<form name="localeForm" action="index.jsp" method="post">
<b>Locale:</b>

126

The source code for this example is in the Java WSDP's


tutorial/examples/web/date directory. As you can see, it is a mixture of
static HTML markup and JSP elements.
If you have developed Web pages, you are probably familiar with the
HTML document structure statements (<head>, <body>, and so on) and
the HTML statements that create a form <form> and a menu <select>.
The 3 directives (<%@page ... %>) import classes in the java.util package
and the MyLocales class, and set the content type returned by the page.
The jsp:useBean element creates an object containing a collection of
locales and initializes a variable that points to that object.

126

05/04/2007

Date Example
<select name=locale>
<%
Iterator i = locales.getLocaleNames().iterator();
String selectedLocale = request.getParameter("locale");
while (i.hasNext()) {
String locale = (String)i.next();
if (selectedLocale != null && selectedLocale.equals(locale) )
{ %>
<option selected><%=locale%></option>
<%
} else { %>
<option><%=locale%></option>
<%
}
}
%>
</select>
<input type="submit" name="Submit" value="Get Date">
</form>
127

Scriptlets (<% ... %> ) retrieve the value of the locale request parameter,
iterate over a collection of locale names, and conditionally insert HTML
text into the output.
Expressions (<%= ... %>) insert the value of the locale name into the
response.

127

05/04/2007

Date Example
<p>
<jsp:include page="date.jsp" flush="true" />
</body>
</html>

128

The jsp:include element sends a request to another page (date.jsp) and


includes the response in the response from the calling page.

128

05/04/2007

Passion!

129

129

Vous aimerez peut-être aussi