Sunteți pe pagina 1din 129

02/27/2006

Java Server Pages (JSP) Basics


1

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.

02/27/2006

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

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

02/27/2006

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)

02/27/2006

Sub-topics of JSP

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

02/27/2006

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.

02/27/2006

Advanced Topics of Servlet/JSP


? ? ? ? ?

MVC (Model-View-Controller) Pattern Model 2 Framework Apache Struts Java Server Faces (JSR 127) Sun Java Studio Application Framework (JATO) 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.

02/27/2006

Agenda
? ? ? ?

? ?

? ?

JSP in big picture of J2EE 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.

02/27/2006

JSP in a Big Picture of J2EE


8

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

02/27/2006

JSP & Servlet in J2EE 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.

02/27/2006

What do you mean by Static & Dynamic Contents?


?

Static contents

Typically static HTML page Same display for everyone Contents is dynamically generated based on conditions Conditions could be
? ? ?

Dynamic contents

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

Examples
Etrade webpage customized just for you, my Yahoo

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.

02/27/2006

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

02/27/2006

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 Java code Displaying properties of JavaBeans Invoking business logic defined in Custom tags

Dynamic content

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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


16

? ?

Easier to author web pages Platform-independent

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

02/27/2006

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

02/27/2006

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

02/27/2006

JSP Benefits Over Technologies (I am not saying JSP is always better...)


?

Versus ASP or Cold Fusion:


Better language for dynamic part Portable to multiple servers and operating systems Is extensible with custom tag libraries

Versus PHP:
Better language for dynamic part Better tool support

Versus pure servlets:


Easier to create HTML Can use standard tools Separate business logic from the presentation
19

This is a comparison of JSP with other technologies. Before I say anything about this, let me say this upfront. I am not saying that JSP is a better technology over the others all the time or you have to use a single technology for all your dynamic contents generation needs. Just like I said in previous slide describing how servlet and JSP are being used together, in many environments, all of these technologies are being used together. And I will let you read the slide for actual benefits of JSP over these technologies.

19

02/27/2006

JSP Architecture
20

Now let's talk about JSP architecture.

20

02/27/2006

Web Application Designs

21

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.

21

02/27/2006

Separate Request processing From Servlet Presentation


Request processing

Pure Servlet
Public class OrderServlet { public void doGet(){ if(isOrderValid (req)){ saveOrder(req ); out.println(<html>); out.println(<body>); private void isOrderValid(.){ } private void saveOrder (.){ } }

Public class OrderServlet{ public void doGet(){ if(bean.isOrderValid (..)){ bean.saveOrder(.); forward(conf. jsp); } }

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

JavaBeans
isOrderValid( )
Business logic

saveOrder( ) 22

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.

22

02/27/2006

JSP Architecture

23

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.

23

02/27/2006

Life-Cycle of a JSP Page


24

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.

24

02/27/2006

How Does JSP Work?


User Request Server File JSP Changed ?

Create Source Compile

Execute Servlet
25

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.

25

02/27/2006

JSP Page Lifecycle Phases


? ? ?

Translation phase Compile phase Execution phase

26

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.

26

02/27/2006

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

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

27

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

27

02/27/2006

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

28

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.

28

02/27/2006

JSP Lifecycle Methods during Execution Phase

29

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.

29

02/27/2006

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 jstInit() method of JspPage interface

30

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.

30

02/27/2006

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 jstDestroy() method of JspPage interface

31

You release resources using the jspDestroy() method. The methods are defined using JSP declarations.

31

02/27/2006

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; } %>


32

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

32

02/27/2006

Steps for Developing JSP-based Web Application


33

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

33

02/27/2006

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

34

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.

34

02/27/2006

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

35

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.

35

02/27/2006

Development Tree Structure


?

Keep Web application source separate from compiled files

facilitate iterative development 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

Root directory

36

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.

36

02/27/2006

Example: Hello2 Example Tree Structure (before ant build command) hello2 directory
?

web directory ? duke.waving.gif ? greeting.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)
37

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.

37

02/27/2006

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

38

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.

38

02/27/2006

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

39

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.

39

02/27/2006

web.xml for Hello2


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

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>

40

02/27/2006

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
41

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.

41

02/27/2006

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
42

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.

42

02/27/2006

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

43

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.

43

02/27/2006

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 Copying *.war file or unpacked directory to <tomcatinstall>/webapps/ directory manually and then restart Tomcat
44

Manual Method

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.

44

02/27/2006

6. Perform Client Access to Web Application


?

From a browser, go to URN of the Web application

http://localhost:8080/hello2/greeting

45

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

45

02/27/2006

http://localhost:8080/hello2/greeting

46

So for the hello1 example web application, a client will specify http://localhost:8080/hello2/greeting to access the web resource.

46

02/27/2006

response.jsp

47

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

47

02/27/2006

Comparing Hello1 Servlet & Hello2 JSP code


48

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

48

02/27/2006

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>");

49

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.

49

02/27/2006

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(); }

50

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

50

02/27/2006

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

51

51

02/27/2006

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

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.

52

02/27/2006

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."; } }

53

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

53

02/27/2006

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

54

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

54

02/27/2006

JSP is Servlet!
55

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.

55

02/27/2006

JSP is Servlet
?

JSP pages get translated into servlet

Tomcat translates greeting.jsp into greeting$jsp.java

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

56

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.

56

02/27/2006

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

57

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

57

02/27/2006

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;

58

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.

58

02/27/2006

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();
59

And in this code, those variables are initialized.

59

02/27/2006

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

60

This code deals with generating HTML pages.

60

02/27/2006

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); } } } 61

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.

61

02/27/2006

Dynamic Content Generation Techniques in JSP

62

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.

62

02/27/2006

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 reusability of code, maintenability, degree of robustness

Simple to incrementally complex techniques are available

63

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.

63

02/27/2006

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 Model2 frameworks
64

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.

64

02/27/2006

(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

65

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.

65

02/27/2006

(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 reusability and maintainability than the previous method Still weak separation between contents and presentation

66

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.

66

02/27/2006

(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 reusability and maintainability than the previous method
67

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.

67

02/27/2006

(d) Develop and Use Custom Tags


?

Develop sophisticated components called custom tags

Custom tags are specifically designed for JSP More than just getter and setter methods

More powerful than JavaBeans component

Reusability, maintainability, robustness

68

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.

68

02/27/2006

(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 J2EE platform at a minimum

As a developer or deployer, you can be assured that a standard set of custom tags are already present in J2EE compliant platform (J2EE 1.3 and after)

69

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.

69

02/27/2006

(f, g) Use MVC Design Pattern


? ?

Follow MVC design pattern Or use open source or commercial Model2 frameworks

Apache Struts JavaServer Faces Sun Java Studio Application Framework Other frameworks: Echo, Tapestry

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

Example: Expressions
?

Display current time using Date class

Current time: <%= new java.util.Date() %> Random number: <%= Math.random() %> Your hostname: <%= request.getRemoteHost() %> Your parameter: <%= request. getParameter (yourParameter) %> Server: <%= application.getServerInfo() %> Session ID: <%= session.getId() %>
74

Display random number using Math class

Use implicit objects


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

02/27/2006

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

02/27/2006

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 2nd example, response type is set through HttpServletResponse implicit object.

76

02/27/2006

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

02/27/2006

Example: Scriptlet Result

78

And this is the output.

78

02/27/2006

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

02/27/2006

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

02/27/2006

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 2nd format is supported only in JSP 1.2.

81

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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> XML validation (via XML schema) Many other XML tools ? editor ? transformer ? Java APIs
85

You can leverage


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

02/27/2006

Including and Forwarding to Other Web Resource


86

86

02/27/2006

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

02/27/2006

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

02/27/2006

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 <jsp:include page="includedPage" /> <jsp:include page="date.jsp"/>
89

Syntax and example


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

02/27/2006

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

02/27/2006

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

02/27/2006

Directives
92

92

02/27/2006

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

02/27/2006

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

02/27/2006

Page Directives
?

Give high-level information about the servlet that results from the JSP page. Control
Which classes are improted
<%@ 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

02/27/2006

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

02/27/2006

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

02/27/2006

Scope Objects
98

98

02/27/2006

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

02/27/2006

Session, Application Scope


Client 1 Session ID 1 server

Session 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

02/27/2006

Session, Request, Page Scope


client

request

response

request

response

Page 1

forward

Page 2

Page 3

forward

Page 4

Page scope request scope

Page scope

Page scope

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

02/27/2006

JavaBeans Components for JSP


102

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

102

02/27/2006

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

02/27/2006

JavaBeans Design Conventions


? ?

JavaBeans maintain internal properties A property can be


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

Properties should be accessed and set via getXxx and setXxx methods

PropertyClass getProperty() { ... } PropertyClass getProperty() { ... }

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

Why Use JavaBeans in JSP Page?


? ?

? ?

No need to learn Java programming language for page designers Stronger separation between content and presentation Higher reusability 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

02/27/2006

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

02/27/2006

Setting JavaBeans Properties


? ?

2 ways to set a property of a bean Via scriptlet

<% beanName.setPropName(value); %> <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

Via JSP:setProperty

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

Getting JavaBeans Properties & and Convert into String and insert into out
?

2 ways via scriptlet


?

<%= beanName.getPropName() %> <jsp:getProperty name="beanName" property="propName"/>

via JSP:setProperty
?

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

02/27/2006

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

02/27/2006

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

02/27/2006

Error Handling
119

119

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

Date Example

124

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

124

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

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

02/27/2006

Passion!

129

129

S-ar putea să vă placă și