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

4th Dimension Systems

1/28/2014

4th Dimension Systems Confidential

Introduction to JSP
JSP enables you to mix static HTML with dynamically generated content.
Servlets look like regular Java programs. JSP pages look like regular HTML pages.

JSP pages are therefore a good option for controlling the look and feel of the page.
1/28/2014 4th Dimension Systems Confidential 2

A Servlets Job
Read explicit data sent by client (form data) Read implicit data sent by client(request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client

(status codes and response headers)

1/28/2014

4th Dimension Systems Confidential

What is JSP?
Mostly HTML page, with extension .jsp Include JSP tags to enable dynamic content creation Translation: JSP Servlet class Compiled at Request time

(first request, a little slow) Execution: Request JSP Servlet's service method

1/28/2014

4th Dimension Systems Confidential

What is a JSP?
<html> <body> <jsp:useBean.../> <jsp:getProperty.../> <jsp:getProperty.../> </body> </html>

1/28/2014

4th Dimension Systems Confidential

Advantages
Code -- Computation
HTML -- Presentation Separation of Roles Developers Content Authors/Graphic Designers/Web Masters Supposed to be cheaper... but not really...

1/28/2014

4th Dimension Systems Confidential

Model-View-Controller
A Design Pattern

Controller -- receives user interface input, updates

data model Model -- represents state of the world (e.g. shopping cart) View -- looks at model and generates an appropriate user interface to present the data and allow for further input

1/28/2014

4th Dimension Systems Confidential

Model-View-Controller
JSP View

Bean
Model Controller Servlet

1/28/2014

4th Dimension Systems Confidential

Servlet

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

Public class OrderServlet { public void doGet(){ if(bean.isOrderValid()){ bean.saveOrder(req); forward(conf.jsp); } } <html> <body> <c:forEach items=${order}> </c:forEach> </body> </html>

JSP

isOrderValid() saveOrder()

Java Bean

-----------------private state

1/28/2014

4th Dimension Systems Confidential

JSP Big Picture


GET /hello.jsp

Hello.jsp

<html>Hello!</html>

HelloServlet.java

Server w/ JSP Container


1/28/2014 4th Dimension Systems Confidential

HelloServlet.class
10

A JSP File

1/28/2014

4th Dimension Systems Confidential

11

Common tags

1/28/2014

4th Dimension Systems Confidential

12

Tag Directives
The directive tag provides additional information to

the JSP Engine regarding the jsp page. JSP directives change the way JSP Engine processes the page. Directive tag allows the user to import packages. Define error handling pages or session information of JSP page. JSP defines three types of directive tag.

page include taglib

1/28/2014

4th Dimension Systems Confidential

13

Directive
Page Directive
Page directive sets page-level preferences for the JSP. Syntax: <%@ page optional attribute ... %> e.g. <%@page language="java" %>

Include Directive
include directive allows the developer to include other JSP or static page when JSP is translated into a servlet, while the action <jsp:include> includes the resources at request time. Syntax: <%@ include optional attribute ... %> e.g.: <%@ include file="/header.jsp" %>

Include Directive
This directive allows the user to create their own custom tags. Syntax: <%@ taglib optional attribute ... %> e.g.: <%@ taglib prefix="x" uri=taglib/mytag.tld" %>
1/28/2014 4th Dimension Systems Confidential 14

Page Directive
There are several options to the page directive.

<%@ page import="java.util.*" %> //example import <%@ page contentType="text/html" %> //example contentType <%@ page isErrorPage=false %> //example for non error page <%@ page isThreadSafe=true %> //example for a thread safe JSP

Note: Only the "import" page directive can be used multiple times in the same JSP.
1/28/2014 4th Dimension Systems Confidential 15

Directive
Example: <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <%@ include .%> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

1/28/2014

4th Dimension Systems Confidential

16

JSPComment
<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

1/28/2014

4th Dimension Systems Confidential

17

Template Text
<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

1/28/2014

4th Dimension Systems Confidential

18

Taglib Directive
This directive allows the page to use user defined tags.
<%@ taglib uri=tagLibraryURI prefix =tagPrefix>

URI:
A URI that identified the tag library descriptor. A tag library descriptor is used to uniquely name the set of custom tags and tells the container what to do with specified tags.

Tagprefix:
Define the prefix string in <prefix>:<tagName> that is used to define in the custom tag.

Eample:
<%@ taglib uri=ttp://www..myserver.com/mytags prefix=saumitra> .. <saumitra:processElement> . </saumitra:processElement>

1/28/2014

4th Dimension Systems Confidential

19

Scripting Element
Scripting Element
Used to include for scripting code ( Normally java code). They allow you to do declare the variable and method Include arbitrary scripting code. Evaluate an expression.

Types of scripting Element


Declaration Scriptlets Expression
1/28/2014 4th Dimension Systems Confidential 20

Declaration
A declaration is a block of java code in JSP.
Used to define class wide variables and method. Initialize when the JSP page initialize and have class scope A Declaration is a block is enclosed between <%! And %>

Exaple:
<%! private int i = 4; public void myMethod(){ // Do some work here } %>
4th Dimension Systems Confidential 21

1/28/2014

Scriptlets
A scriptlet is a block of java code
That is executed at request processing time Scriptlets is enclosed between <% and %>.

Simple analogy is
JSP get compiled into a servlet All code appearing between <% and %> in the JSP put into the service() method. In the same order it appears.

Example
<% for(int i = 0; i < 10 i++){ //Do something } %>
1/28/2014 4th Dimension Systems Confidential 22

Expression
An Expression is a
Shorthand notation for scriptlet. Output the value in the response stream back to the client. When the expression is evaluated, the result is converted into string and displayed. An expression is enclosed within <%= and %>

Example
<%! int count = 0 %> <% count++ %> Count: = <%= count %>
1/28/2014 4th Dimension Systems Confidential 23

Standard Actions
Actions are specific tag that
Affects the run time behavior of JSP. Affects the response sent back to the client. JSP Specifications lists some action that are standard.

The Standard Action types are:


<jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:param> <jsp:forward> <jsp:include> <jsp:plugin>
4th Dimension Systems Confidential 24

1/28/2014

JSP: useBean
A useBean action is associated a javaBean with the JSP
Ensure the object is available for the appropriate scope specified in the tag. The bound object can be referred from the id. Internally container first tries to locate the object using id and scope. If not it is not found uses the name of the bean as an argument to the instantiate() method of the java.beans.Beans using the current class loader.

Sysntax:
<jsp:useBean id=name scope=page|request|session|application beandetails/>

Beandetails is one of the following


class=className class=className type=typeName beanName=beanName type=typeName type=typeName
4th Dimension Systems Confidential 25

1/28/2014

Scope Attribute
Page
Object reference is discarded upon the completion of current Servlet.service() invocation

Request
The object reference is available as long as the HttpRequest object is not discarded. HttpServletRequest object is distinct for every client request

Session
The object is dictint for every client

application
This is most persistent Binding with ServletContext Not unique for clients

1/28/2014

4th Dimension Systems Confidential

26

Jsp:setProperty
This is used in conjunction with the useBean action. The properties in a bean can be set either:
At request time from parameters in the request objects Or at request time from an evaluated expression. Or from a specified string.

Syntax:
<jsp:setProperty name=beanName propertlyetails>

Where the propertydetails is one of the


Property=* Property=propertyName Property=propertyName param=parameterName Property=propertyName value=propertyValue
4th Dimension Systems Confidential 27

1/28/2014

Jsp:getProperty
This is complementary to the jsp:setProperty.
Sysntax:
<jsp:getProperty name=beanName property=propertyName />

Example
<jsp:useBean id="calendar" scope="page" class="employee.Calendar" /> <h2> Calendar of <jsp:getProperty name="calendar" property="username" /> </h2>
1/28/2014 4th Dimension Systems Confidential 28

Jsp:param
The jsp:param action is used to provide other tags with additional information in the form of name-value pairs. The action is is used in conjunction with jsp:include, jsp:forward and jsp:plugin action. Syntax:
<jsp:param name=paramname value=paramvalue>

1/28/2014

4th Dimension Systems Confidential

29

Jsp:include
The <jsp:include> element allows you to include either a static or dynamic resource in a JSP page. The results of including static and dynamic resources are quite different
If the resource is static, its content is included in the calling JSP page If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page When the include action is finished, the JSP container continues processing the remainder of the JSP page.

Sysntax
<jsp:include page="{relativeURL | <%= expression %>}" flush="true| false" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:include>
4th Dimension Systems Confidential 30

1/28/2014

JSP:include

Example
<jsp:include page="scripts/login.jsp" /> <jsp:include page="copyright.html" /> <jsp:include page="/index.html" /> <jsp:include page="scripts/login.jsp">
<jsp:param name="username" value="jsmith" />

</jsp:include>
1/28/2014 4th Dimension Systems Confidential 31

jsp:forward
The <jsp:forward> element forwards the request object containing the client request information from one JSP page to another resource.
The target resource can be an HTML file, another JSP page, or a servlet, as long as it is in the same application context as the forwarding JSP page. The lines in the source JSP page after the <jsp:forward> element are not processed

Syntax:
<jsp:forward page="{relativeURL | <%= expression %>}" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> + </jsp:forward>

Example:
<jsp:forward page="/servlet/login" /> <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>
1/28/2014 4th Dimension Systems Confidential 32

Jsp:plugin
The <jsp:plugin> element plays or dispays an object (typically an applet or bean) in the client web browser, using a Java plug-in that is built in to the browser or downloaded from a specified URL.
Syntax
<jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [ name="instanceName" ] [ archive="URIToArchive, ..." ] [ align="bottom|top|middle|left|right" ] [ height="{displayPixels | <%= expression %>}"] [ width="{displayPixels | <%= expression %>}"] [ hspace="leftRightPixels" ] [ vspace="topBottomPixels" ] [ jreversion="JREVersionNumber | 1.2" ] [ nspluginurl="URLToPlugin" ] [ iepluginurl="URLToPlugin" ] > [ <jsp:params> [ <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> ]+ </jsp:params> ] [ <jsp:fallback> text message for user </jsp:fallback> ] </jsp:plugin>

1/28/2014

4th Dimension Systems Confidential

33

Jsp:plugin
Example:
<jsp:plugin type=applet code="Molecule.class" codebase="/html"> <jsp:params> <jsp:param name="molecule" value="molecules/benzene.mol" /> </jsp:params> <jsp:fallback> <p>Unable to load applet</p> </jsp:fallback> </jsp:plugin>
1/28/2014 4th Dimension Systems Confidential 34

JSP Implicit Objects


request object
The object request is of type Javax.servlet.http.httpservletrequest

response object
The object response is of type Javax.servlet.http.httpservletresponse

session object
The object Session is of type Javax.servlet.http.httpsession

out object
This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter

pageContext object
This is used to access page attributes and also to access all the namespaces associated with a JSP page.
1/28/2014 4th Dimension Systems Confidential 35

JSP Implicit Objects Contn.


application object
This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext.

config object
This is used to get information regarding the Servlet configuration, stored in the Config object.

page object
The Page object denotes the JSP page, used for calling any instance of a Page's servlet

excpetion object
The exception object contains the exception which is thrown from the previous JSP page

1/28/2014

4th Dimension Systems Confidential

36

Thank You
4th Dimension Systems

1/28/2014

4th Dimension Systems Confidential

37

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