Вы находитесь на странице: 1из 30

JSP

Servlet
What is JSP Page?
JSP is a technology based on the Java language and enables development of
dynamic web sites

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

Servlet
JSP
Separation of dynamic and static content
This allows for the separation of application logic and Web page design, reducing the complexity of
Web site development and making the site easier to maintain.

Platform independence
Because JSP technology is Java-based, it is platform independent. JSPs can run on any nearly any
Web application server. JSPs can be developed on any platform and viewed by any browser
because the output of a compiled JSP page is HTML.

Component reuse
Using JavaBeans and Enterprise JavaBeans, JSPs leverage the inherent reusability offered by
these technologies. This enables developers to share components with other developers or their
client community, which can speed up Web site development.

Scripting and tags


JSPs support both embedded JavaScript and tags. JavaScript is typically used to add page-level
functionality to the JSP. Tags provide an easy way to embed and modify JavaBean properties and to
specify other directives and actions.

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

Output

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.

Servlet
Difference between JSP and Servlet

Servlet
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

Servlet
Why JSP over Servlet?

Servlets can do a lot of things:


Use those println() statements to generate HTML page
Maintain that HTML page not easy.

No need for compiling, packaging,CLASSPATH setting

Servlet
Separate Request processing From Presentation
JSP is the separation of contents generation logic from presentation logic. Here the
contents generation includes business logic processing.

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.

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.

Servlet
Separate Request processing From Presentation

Servlet
JSP Architecture

Servlet
JSP Architecture
The Web browser makes a request to the JSP page.

The JSP engine parses the contents of the JSP file.

The JSP engine creates temporary servlet source code based on the contents of
the JSP. The generated servlet is responsible for rendering the static elements of
the JSP specified at design time in addition to creating the dynamic elements of the
page.

The servlet source code is compiled by the Java compiler into a servlet class file.

The servlet is instantiated. The init and service methods of the servlet are called,
and the servlet logic is executed.

The combination of static HTML and graphics combined with the dynamic elements
specified in the original JSP page definition are sent to the Web browser through the
output stream of the servlets response object.

Servlet
Java Server Pages
JSP is a technology based on the Does not embed HTML into Java
Java language and enables
development of dynamic web Embeds special active elements
sites (Java) into HTML pages

JSP was developed by Sun JSP is a specification, not a


Microsystems to allow server side product
development
Not necessary to compile and
JSP Files are HTML files with install JSPs yourself
special tags containing Java code
that provide dynamic content Changes made to the JSP files
result in immediate reflection on
the Web site

Servlet
JSP Page Lifecycle Phases

Translation phase
translation phase in which a JSP page gets translated into a servlet code,

Compile phase
compilation phase in which servlet code gets compiled

Execution phase
execution phase in which servlet instance then serves client request. Usually
translation and compilation phases occur together.

Servlet
Translation/Compilation Phase
A JSP page gets translated and compiled automatically if there is no complied class already. So
if you deploy JSP page for the first time.

if you modified the JSP page, then translation and compilation will occur

It was Done by the container automatically

During the translation phase, each type of data in a JSP page is treated differently

Static data
Static data (called as template data) is transformed into Java code that will emit the data into the
output stream which returns data to the client.

Dynamic data
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.

Servlet
JSP Lifecycle Methods during Execution Phase
If an instance of the JSP page's servlet does not exist, the container Loads the
JSP page's servlet class

Container then creates an instance of the servlet class

Container then initializes the servlet instance by calling the jspInit method

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.

Servlet
Initialization of a JSP Page

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.

jspService() method is also responsible for generating responses to all the


HTTP methods.

Servlet
Components of Java Server Pages

Directives

Declarations

Scriptlets

Comments

Expressions

Servlet
JSP directives
Directives provide additional information to the JSP container and describe attributes for page

The directives do not produce any output to the current output stream.

Directive Purpose

page Controls properties of the JSP

include Includes the contents of a file into the JSP at translation time
taglib Makes a custom tag library available within the including page

syntax :
< % @ directive [ attr = "value ] % >

Or

< jsp:directive. directive [ attr = value ] />

Servlet
The page directive

The page directive defines various page-dependent properties and


communicates these to the JSP container.

<%@ page [attribute="value"*] %>


or
<jsp:directive.page [attribute="value"*] />

Servlet
Ex :

<jsp:directive.page import="java.util.Date"/>

<HTML>

<HEAD><TITLE>Hello World JSP Example w/Current Time</TITLE></HEAD>

<BODY>
Hello World.
The local server time is <%= new Date() %>.
</BODY> </HTML>

This directive causes java.util.Date to be imported (as in the Java


statement import java.util.Date ) into JSP.

Servlet
page directive attributes
Other page attributes control page buffering, exception handling, the scripting
language, and so forth.

Attribute Use

language This attribute defines the scripting language to be used in the scriptlets,
expressions, and declarations within the body of the translation unit
extends Specifies the superclass of the class to which this JSP is transformed. It
should be defined as a fully qualified class name. It is implementation-
dependent, and you should use it with caution. Each implementation
provides its own default class; overriding the default can affect the quality
of the implementation.
import Describes all Java types available as imports. It follows the same rules as
standard Java language import statements. By default, java.lang.*,
javax.servlet.http.*, javax.servlet.*, and javax.servlet.jsp.* are imported. You
can add any additional packages or types you need imported for your page.

Servlet
Session Indicates whether the page requires participation in an HttpSession. By
default, the value is true. You have the option of specifying the value as false
(in that case, any reference to HttpSession in the page will not be resolved).
buffer This page attribute indicates whether the content output from the page will be
buffered. By default, the page output is buffered with an implementation
buffer size no smaller than 8 KB.
autoFlush Specifies whether the buffered output should be flushed automatically (true
value) when the buffer is filled, or whether an exception should be raised
(false value) to indica
info Defines a string that can be incorporated into the translated page.
isErrorPage Indicates if the current JSP is the intended target of another JSP's errorPage.
The default value is false.
ErrorPage Defines a URL to a resource that will catch the current page's exception.
ContentType Defines the MIME type and the character encoding for the response of the
JSP. Values are either of the form "TYPE" or "TYPE;charset= CHARSET".
pageEncoding Defines a URL to a resource that will catch the current page's exception.

Servlet
The include directive
The include directive includes the content of the named file directly into JSP's
source, as it is compiled. The two ways to write a JSP include directive:

<%@ include file="filename" %>


or
<jsp:directive.include file="filename" />

EX :
<jsp:directive.include file="/copyright.html" />
<HTML>
<HEAD><TITLE>Hello World JSP Example</TITLE></HEAD>
<BODY>
Hello World.
</BODY>
</HTML>

The included file becomes part of JSP page when the page is translated.

Servlet
The taglib directive
The ability to create and use custom tag libraries is one of the most powerful and
useful features JSP offers.

This feature enables developers to define new XML-style tags for use by page
designers;

the JSP specification refers to these new tags as new actions.

All the details can be encapsulated within the custom tags.

JSPs that use custom tags have a much cleaner separation of interface design
and business logic implementation than JSPs with a lot of embedded Java code

Servlet
Example
<jsp:directive.taglib uri="jdg.tld" prefix="jdg" />
<HTML>
<HEAD><TITLE>Hello World JSP Example w/Current
Time</TITLE></HEAD>
<BODY>
Hello World.
The local server time is <jdg:DATE />.
</BODY>
</HTML>
The first line is a taglib directive.
The uri attribute tells the JSP container where to find the taglib definition.
The prefix attribute tells the JSP container that will use jdg: as a prefix for the tag.
This prefix is mandatory and prevents namespace collisions.
The jsp prefix is reserved by Sun.
The tag <jdg:DATE /> results in the use of a custom tag handler class. In this
handler class, the current date and time are put into the output stream.

Servlet
JSP declarations

Declarations declare new data and function members for use within
the JSP.
JSP declaration in two ways:
<%! java declarations % >
or
< jsp: declaration > java declarations < / jsp:declaration >

Servlet
JSP declaration example
To uses a JSP declaration to declare a class variable and some class functions.

<jsp:directive.page import="java.util.Date"/>
<jsp:declaration>
private static String loadTime = new Date().toString(); // variable
private static String getLoadTime() // function
{
return loadTime;
}
private static String getCurrentTime() //function
{
return new Date().toString();
}
</jsp:declaration>
<HTML>
<HEAD><TITLE>Hello World JSP Example</TITLE></HEAD>
<BODY>
Hello World.<BR>
This page was loaded into memory at <%= getLoadTime() %>.<BR>
The current time is <%= getCurrentTime() %>
</BODY>
</HTML>

Servlet
JSP expressions

Expressions in Java code are statements that result in a value.. A


JSP expression is a Java expression evaluated at request time,
converted to a String, and written into the output stream.

JSP expressions are written either as:

<%= a-java-expression %>


or
<jsp:expression> a-java-expression </jsp:expression>

Example :

The local server time is <%= new java.util.Date() %>.


The text <%= new java.util.Date() %> is a JSP expression.

Servlet
JSP scriptlets

Scriptlets are (more or less) small sets of statements written in the


scripting language.

Scriptlets are executed at request processing time. Whether they


produce any output into the output stream depends on the code in
the scriptlet.

<% java-statements %>


or
<jsp:scriptlet>
java-statements
</jsp:scriptlet>

Servlet
Scriptlet example
The following JSP uses scriptlets to execute differently depending on the browser
<jsp:scriptlet>
String userAgent = (String) request.getHeader("user-agent");
</jsp:scriptlet>
<HTML>
<HEAD><TITLE>JSP Scriptlet Example</TITLE></HEAD>
<BODY>
<jsp:scriptlet>
if (userAgent.indexOf("MSIE") != -1)
{
</jsp:scriptlet>
<p>You are using Internet Microsoft Explorer.</p>
<jsp:scriptlet>
}
else
{
</jsp:scriptlet>
<p>You are not using Internet Microsoft Explorer.
You are using <%= userAgent %></p>
<jsp:scriptlet>
}
</jsp:scriptlet>
</BODY> </HTML>

Servlet

Вам также может понравиться