Está en la página 1de 20

JSP Tutorial

JSP

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, SVG, WML, and XML; and JSP elements, which construct dynamic content. A JSP page has extension .jsp example hello.jsp

The Life Cycle of a JSP Page

A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology

When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.

Translation and Compilation

During the translation phase, each type of data in a JSP page is treated differently. Template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows: Directives are used to control how the Web container translates and executes the JSP page. Scripting elements are inserted into the JSP page's servlet class. Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API.

Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete. The last incomplete line will give a pointer to the incorrect JSP element.

Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. If an instance of the servlet does not exist, the Web container

Loads the servlet class. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method.

Invokes the service method, passing a request and response object. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.

JSP Life Cycle

Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle described in the Servlet Life Cycle: If an instance of the JSP page's servlet does not exist, the container:

Loads the JSP page's servlet class Instantiates an instance of the servlet class Initializes the servlet instance by calling the jspInit method

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.

Execution

You can control various JSP page execution parameters using by page directives.

Creating Static Content

You create static content in a JSP page by simply writing it as if you were creating a page that consisted only of that content. Static content can be expressed in any text-based format, such as HTML, WML, and XML. The default format is HTML. If you want to use a format other than HTML, you include a page directive with the contentType attribute set to the format type at the beginning of your JSP page. For example, if you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive:

<%@ page contentType="text/vnd.wap.wml"%>

Creating Dynamic Content

You can create dynamic content by accessing Java programming language objects from within scripting elements.

Using Objects within JSP Pages


You can access a variety of objects, including enterprise beans and JavaBeans components, within a JSP page. JSP technology automatically makes some objects available, and you can also create and access application-specific objects.

Implicit Objects

application The context for the JSP page's servlet and any Web components contained in the same application. config Initialization information for the JSP page's servlet. exception Accessible only from an error page. out The output stream. page The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors. pageContext The context for the JSP page. Provides a single API to manage the various scoped attributes. request The request triggering the execution of the JSP page. response The response to be returned to the client. Not typically used by JSP page authors. session The session object for the client.

Application-Specific Objects

When possible, application behavior should be encapsulated in objects so that page designers can focus on presentation issues. Objects can be created by developers who are proficient in the Java programming language and in accessing databases and other services. There are four ways to create and use objects within a JSP page:
Instance and class variables of the JSP page's servlet class are created in declarations and accessed in scriptlets and expressions. Local variables of the JSP page's servlet class are created and used in scriptlets and expressions. Attributes of scope objects are created and used in scriptlets and expressions. JavaBeans components can be created and accessed using streamlined JSP elements. You can also create a JavaBeans component in a declaration or scriptlet and invoke the methods of a JavaBeans component in a scriptlet or expression.

1.

2. 3. 4.

Shared Objects

The conditions affecting concurrent access to shared objects apply to objects accessed from JSP pages that run as multithreaded servlets. You can indicate how a Web container should dispatch multiple client requests with the following page directive: <%@ page isThreadSafe="true|false" %>

When isThreadSafe is set to true, the Web container may choose to dispatch multiple concurrent client requests to the JSP page. This is the default setting. If using true, you must ensure that you properly synchronize access to any shared objects defined at the page level. This includes objects created within declarations, JavaBeans components with page scope, and attributes of the page scope object.
If isThreadSafe is set to false, requests are dispatched one at a time, in the order they were received, and access to page-level objects does not have to be controlled. However, you still must ensure that access to attributes of the application or session scope objects and to JavaBeans components with application or session scope is properly synchronized.

JSP Scripting Elements

JSP scripting elements are used to create and access objects, define methods, and manage the flow of control. Since one of the goals of JSP technology is to separate static template data from the code needed to dynamically generate content, very sparing use of JSP scripting is recommended. Much of the work that requires the use of scripts can be eliminated by using custom tags. JSP technology allows a container to support any scripting language that can call Java objects. If you wish to use a scripting language other than the default, java, you must specify it in a page directive at the beginning of a JSP page: <%@ page language="scripting language" %> Since scripting elements are converted to programming language statements in the JSP page's servlet class, you must import any classes and packages used by a JSP page. If the page language is java, you import a class or package with the page directive: <%@ page import="packagename.*, fully_qualified_classname" %> For example, the bookstore example page showcart.jsp imports the classes needed to implement the shopping cart with the following directive: <%@ page import="java.util.*, cart.*" %>

Declarations

A JSP declaration is used to declare variables and methods in a page's scripting language. The syntax for a declaration is as follows: <%! scripting language declaration %> When the scripting language is the Java programming language, variables and methods in JSP declarations become declarations in the JSP page's servlet class.

The bookstore example page initdestroy.jsp defines an instance variable named bookDBEJB and the initialization and finalization methods jspInit and jspDestroy discussed earlier in a declaration:
<%!
private BookDBEJB bookDBEJB; public void jspInit() { ... } public void jspDestroy() { ... }

%>

Scriptlets

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

%> Example
<%

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

Expressions

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. The syntax for an expression is as follows:
<%= scripting language 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.

Including Content in a JSP Page

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

1. 2.

The include directive

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 containing the banner content with the following directive: <%@ include file="banner.jsp" %>

The jsp:include element

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 as follows: <jsp:include page="includedPage" /> The example to includes the page that generates the display of the localized date with the following statement: <jsp:include page="date.jsp"/>

Transferring Control to Another Web Component

The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API. You access this functionality from a JSP page with the jsp:forward element:
<jsp:forward page="/main.jsp" />

También podría gustarte