Java server pages (jsp)
-
Upload
online-it-training -
Category
Education
-
view
68 -
download
3
description
Transcript of Java server pages (jsp)
Java Server Pages (JSP)Java Server Pages (JSP)
• Adds dynamic content generation capabilities to static templates
• Standard web access layer to Java 2 Enterprise Edition (J2EE)
• Builds on Java Servlet technology
• Leverages JavaBeans™ Architecture
• Extensible via custom tags
What Is JSP?
JSP
Servlets and JSP - Comparison
• HTML code in Java
• Any form of Data• Not easy to author• Underlying
semantics
• HTML code in Java
• Any form of Data• Not easy to author• Underlying
semantics
• Java-like code in HTML
• Structured Text• Very easy to author• Code is compiled into
a servlet
• Java-like code in HTML
• Structured Text• Very easy to author• Code is compiled into
a servlet
Servlets
Java Server Pages (JSP)
• The capability to mix static HTML with dynamically generated content from servletsüTake the presentation out of the servlet
• The dynamic parts are enclosed in special tagsü<% … %>
JSP Advantages
• Supported by all major web/application server vendorsüNot locked into a single OS or web server
• Builds on what we have learned alreadyüServlets and Java
How it works
• Using any editor, or HTML Tool create a file that ends with .jsp
• Put the file anywhere on your web serverüYou don’t have to worry about compiling
the file, your CLASSPATH, etc.üThe web server takes care of it
How it works…
• The first time the page is requested the .jsp file is converted into a servlet, compiled, and startedüAll of the code is place into the service()
method
• If you have any errors in your page Tomcat will return a nice HTML error page
How the JSP Engine Works
Why not just write Servlets?
• The focus is on HTML. Java and the JSP extensions assist in making the HTML morefunctional. Servlets on the other hand allow outputting of HTML but it is a tediousprocess.
• It is easy to make a change and then let the JSP capability of the Web Server you areusing deal with compiling it into a Servlet and running it.
•• The focus is on HTML. Java and the JSP extensions The focus is on HTML. Java and the JSP extensions assist in making the HTML moreassist in making the HTML morefunctional. Servlets on the other hand allow outputting functional. Servlets on the other hand allow outputting of HTML but it is a tediousof HTML but it is a tediousprocess. process.
•• It is easy to make a change and then let the JSP It is easy to make a change and then let the JSP capability of the Web Server you arecapability of the Web Server you areusing deal with compiling it into a using deal with compiling it into a ServletServlet and running and running it. it.
üEasy and Rapid Web Development, Deployment and Maintenance
üEmphasizing Reusable Components
üSeparating Content Generation from Presentation
üOpen Development and Widespread Industry Support
üPlatform Independence
üSimplifying Page Development with Tags
üüEasy and Rapid Web Development, Deployment and Easy and Rapid Web Development, Deployment and MaintenanceMaintenance
üüEmphasizing Reusable ComponentsEmphasizing Reusable Components
üüSeparating Content Generation from PresentationSeparating Content Generation from Presentation
üüOpen Development and Widespread Industry SupportOpen Development and Widespread Industry Support
üüPlatform IndependencePlatform Independence
üüSimplifying Page Development with TagsSimplifying Page Development with Tags
Benefits of JSP
Pass Thru
• All static HTML in a JSP page is simply passed straight through to the client.
• If you need <% in the output use:ü<\% in the text
• To comment the JSP code use:ü<%-- JSP Comment --%>
0Will not appear in the resultant documentü<!-- HTML Comment -->
0Will appear in the resultant document
JSP Scripting Elements
• Lets you insert code into the servlet from the JSP page
• 3 typesüExpressionsüScriptletsüDeclarations
JSP Expressions
• Used to insert values directly into the outputü<%= expression %>üThe expression is evaluated, converted to
a string and placed into the page
• ExampleüMark a page with the current date/time
Scriptlets
• More complex than a simple one-line expressionüA block of Java code
0<% code %>0Inserted into the servlet and is eventually
called by the service() method
üHave access to the same predefined variables
Scriptlets…
• Scriptlets are great for making parts of a JSP File conditional• The JSP code:
<% if (Math.random() < 0.5 { %>Have a <B>nice</B> day!<% } else { %>Have a <B>lousy</B> day!<% } %>
• Gets converted to:if (Math.random() < 0.5 {
out.println(“Have a <B>nice</B> day!”);} else {
out.println(“Have a <B>lousy</B> day!”);}
Declarations
• Methods or Fields that are inserted into the main body of the servlet (not in the service() method)ü<%! code %>
• Declarations do not generate any outputüUsually are helpers for expressions and
scriptlets
Declarations…
• Example, an access counter
<%! private int accessCount = 0; %>Accesses to page since server reboot: <%= ++accessCount %>
Predefined Variables
• Within all JSP elements you have acces to several predefined variablesürequest
0HttpServletRequestüresponse
0HttpServletResponseüsession
0HttpSession associated with the requestüout
0PrintWriter for writing output to the client
JSP Directives
• Affects the structure of the generated servletü <%@ directive attribute=“value”
attribute2=“value2”… %>
• 3 Typesü Page
0Import classes, customize servlet superclass, set content type, etc.
ü Include0Include a file on compilation
ü taglib0Define custom markup tags
Page Directives - import
• The import attribute corresponds to the import statement in JavaüEasier class namingüBy default java.lang, javax.servlet,
javax.servlet.jsp, javax.servlet.http are all imported
• Form & Exampleü <%@ page import=“package.class1, …, package.classN” %>ü <%@ page import=“java.util.*” %>
import…
• import is the only page directive that can appear multiple times in a single document
• Page directives can appear anywhere in a documentüKeep them at the top!
• The classes you import must be in a directory that is in your server’s classpath
contentType Attribute
• Sets the Content-Type response headerüi.e. the MIME Type of the document being
returned
• Formsü<%@ page contentType=“MIME-Type” %>ü<%@ page contentType=“MIME-Type; charset=“Character-Set” %>
• The default MIME-Type for JSP is text/htmlüThe default for servlets is text/plain
contentType Attribute…
• ExampleüSet the content type so the browser
renders the HTML as text
isThreadSafe Attribute
• Formü<% page isThreadSafe=“true” %>ü<% page isThreadSafe=“false” %>
• Default is trueüAssumes you take care of synchronizing
access when it is needed
• Set to false and the servlet will implement the SingleThreadModel
session Attribute
• Controls whether or not the page participates in HTTP Sessions
• Formsü<%@ page session=“true” %>ü<%@ page session=“false” %>
• Default is trueüIf set to false, accesses to the session
variable will result in a compile error.
buffer Attribute
• Specify the size of the buffer used by the out variableüOf type JSPWriter
• Formsü<%@ page buffer=“sizekb” %>ü<%@ page buffer=“none” %>
• Default is server specific, but it can’t less then 8 kilobytesüOnce the buffer size is hit the data is sent to the
clientüCould impact the use of sessions and the setting
of headers (do them early!)
extends Attribute
• Used to modify the superclass of the servlet being generated
• Formü<%@ page extends=“package.class” %>
info Attribute
• Defines the string returned by getServletInfo
• Formü <%@ page info=“What your page does” %>
errorPage Attribute
• Specifies a JSP page that should process any exceptions thrown but not caught by the page
• Formü <%@ page errorPage=“relative URL.jsp” %>
• The error page can access the error via the exception variable
isErrorPage Attribute
• Indicates whether the current page can act as the error page for other JSP pages
• Forms:ü<%@ page isErrorPage=“true” %>ü<%@ page isErrorPage=“false” %>
• Default is false
JSP Syntax Include Directive
• Includes a static file<%@ include file=“relativeURL” %>
Example:main.jsp: <html><body>
Current date and time is:<%@include file=“date.jsp” %>
</body></html>date.jsp: <%@page import =“java.util.*” %>
<% =(new java.util.Date()).toLocaleString() %>Output : Current date and time is:
Mar 5, 2000 4:56:50
Standard Actions
JSP Syntax <jsp:forward>
• Forwards request to another file (HTML, JSP, or Servlet) for processing
<jsp:forward page =“relativeURL” %>
Example:<jsp:forward page=“scripts/login.jsp” />
or<jsp:forward page=“scripts/login.jsp” >
<jsp:param name=“username” value=“jsmith”/></jsp:forward>
JSP Syntax <jsp:include>
• Includes a static or dynamic file<jsp:include page =“relativeURL” %>
Example:<jsp:include page=“scripts/login.jsp” /><jsp:include page=“copyright.html” />
JSP Syntax <jsp:useBean>
• Locates or instantiates a JavaBeans components.
<jsp:useBean id=“beanInstanceName”scope=“page| request | session|
application” class=“package.class” />
Example:<jsp:useBean id=“calendar”scope=“page”
class=“employee.Calendar”/>
Scope and state maintenance in JSP
scope Description
Page Object is accessible only by a single client from the page on which it iscreated.
Request Object is accessible by a single clientfor the lifetime of a single clientrequest.
Session Object is accessible by a single clientfrom anywhere in the application for thelifetime of an entire user session.
Application Object accessible is by any client from
any page within the application for thelifetime of the application.
JSP Syntax <jsp:setProperty>
• Sets the value of one or more properties in a Bean, using the Bean’s setter methods.
• Declare the Bean with <jsp:useBean> first<jsp:setProperty name=“beanInstanceName”
property=“propertyName” value=“string” />
Example:<jsp:useBean id=“calendar”scope=“page”
class=“employee.Calendar”/><jsp:setProperty name=“calendar”
property=“username” value=“Steve”/></H1>
JSP Syntax <jsp:getProperty>
• Gets a Bean property value, using the Bean’s getter methods.
• Declare the Bean with <jsp:useBean> first<jsp:getProperty name=“beanInstanceName”
property=“propertyName” />Example:
<jsp:useBean id=“calendar”scope=“page”class=“employee.Calendar”/>
<H1>Calendar of <jsp:getPropertyname=“calendar”
property=“username”/></H1>
• Model-1 Features:üsuitable for simple applicationsüseparation of presentation from contentünot be suitable for complex implementationüeasily lead to an unclear definition of roles and
allocation of responsibilities.
• Model-2 Features:üsuitable for complex applicationsüclearest separation of presentation from
contentüclear definition of roles and responsibilities of
the developments and page designers.üthe downside of using the Model 2 approach is
its complexity.