Java Server Pages (JSP)

Slides:



Advertisements
Similar presentations
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Advertisements

 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
JSP – Java Server Pages Part 1 Representation and Management of Data on the Internet.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
DT228/3 Web Development JSP: Directives and Scripting elements.
1 CS6320 – JSP L. Grewe 2 Java Server Pages Servlets require you to write out entire page delivered with print statements Servlets require you to write.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
1 JSP – Java Server Pages Representation and Management of Data on the Internet.
What Are Beans? beans are simply Java classes that are written in a standard format. A bean class must have a zero-argument (default) constructor. A bean.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Jordan Anastasiade. All rights reserved.
 Embeds Java code  In HTML tags  When used well  Simple way to generate dynamic web-pages  When misused (complex embedded Java)  Terribly messy.
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaServer Page.
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
Java Server Pages (JSP) Provide a cross-platform framework for creating dynamic web contents JSP Components: Static HTML/XML parts Special JSP Tags Snippets.
1 JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
Chapter 11 Invoking Java Code with JSP Scripting Elements.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
JSP. Types of JSP Scripting Elements Expressions of the form, which are evaluated and inserted into the servlet's output. Scriptlets of the form, which.
Web Technologies Java Beans & JSP By Praveen Kumar G.
Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
1 Chapter 27 JavaServer Page. 2 Objectives F To know what is a JSP page is processed (§27.2). F To comprehend how a JSP page is processed (§27.3). F To.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Chapter 14 Using JavaBeans Components in JSP Documents.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
JSP Action Elements Lec - 37.
JSP: Actions elements and JSTL
Developing JavaServer Pages
Java Server Pages.
Java Server Pages By: Tejashri Udavant..
COMP9321 Web Application Engineering Semester 2, 2017
Scripted Page Web App Development (Java Server Pages)
Pre-assessment Questions
Knowledge Byte In this section, you will learn about:
Invoking Java Code from JSP
Java Server Pages JSP 11/11/2018.
JSP Syntax.
Introduction to Java Server Pages
Java Server Pages.
JSP Directives 1-Jan-19.
JSP implicit objects & directive elements
Introduction.
Introduction to JSP Dept. of B.Voc Software Development and System Administration St. Joseph’s College(Autonomous) Trichy-02 By Dr. J. Ronald Martin Introduction.
Scripted Page Web Application Development (Java Server Pages)
Web Technologies Java Beans & JSP
Presentation transcript:

Java Server Pages (JSP)

Basics Whereas servlets often embed HTML in Java, JSP’s embed Java in HTML JSP’s are translated into servlets and compiled by the web server JSP’s consist of standard HTML, scripting elements, directives, and action elements HTML in the JSP will produce println statements in the generated servlet

HTML in JSP Comments: <!-- HTML Comment --> HTML comments are passed through to the client. <%-- JSP Comment --%> JSP comments are not. To use <% or %> in the HTML use <\% or %\> respectively.

Scripting Elements Expressions: <%= expression %> The generated servlet will evaluate the expression and insert the result in its output Scriptlets: <% code %> The code will be inserted in a method invoked by the servlets service method Declarations: <%! code %> The code is inserted in the servlet class outside of any methods

Alternative XML Syntax Expressions: <jsp:expression> expression </jsp:expression> Scriptlets: <jsp:scriptlet> code </jsp:scriptlet> Declarations: <jsp:declaration> code </jsp:declaration>

Expressions Evaluated at runtime (when page is requested), converted to String, and inserted in the page. Predefined Variables request, the HttpServletRequest response, the HttpServletResponse session, the HttpSession for the request out, a PrintWriter to write to the client application, the ServletContext config, the ServletConfig pageContext, the PageContext page, same as this

Expression Examples JSP Expressions <h2>JSP Expressions</h2> <ul> <li>Current time: <%= new java.util.Date() %> </li> <li>Your hostname: <%= request.getRemoteHost() %></li> <li>Test value: <%= request.getParameter(“test”) %> </li> <li>Your session ID: <%= session.getId() %> </li> </ul> JSP Expressions Current time: Mon Jun 3 11:20:15 EST 2002 Your hostname: moosehead.cis.umassd.edu Test value: some data Your session ID: YTGFREDKI8P6HF43WAXDLKUY

Scriptlets Have access to the same predefined variables as expressions. Allow the inclusion of arbitrary code in the generated servlet. May be interspersed with plain HTML and expressions. Can make parts of page conditional, or generated repeatedly in a loop.

Scriplet Example (1) JSP Code Generated Servlet Code <% if (Math.random() < 0.5) { %> Have a <b>nice</b> day! <% } else { %> Have a <b>lousy</b> day! <% } %> if (Math.random() < 0.5) { out.println(“Have a <b>nice</b> day!”); } else { out.println(“Have a <b>lousy</b> day!”); } JSP Code Generated Servlet Code

Scriptlet Example (2.1) <table border=“1”> <tr><th>A</th><th>B</th></tr> <% while (results.next()) { %> <tr> <td><%= results.getString(1) %></td> <td><%= results.getString(2) %></td> </tr> <% } %> </table>

Scriptlet Example (2.2) out.println(“<table border=\“1\”>”); out.println(“<tr><th>A</th><th>B</th></tr>”); while (results.next()) { out.println(“<tr>”); out.print(“<td>”); out.print((results.getString(1)).toString()); out.println(“</td>”); ...

Declarations Example <%! private int count = 0; %> This page has been accessed <%= ++count %> times since the last server reboot. Note that count need not be static, since there is normally only one instance of each servlet (possibly accessed simultaneously by multiple threads).

<%@ page attribute=“value” … %> Page Directives <%@ page attribute=“value” … %> import attribute classes and packages used on the page may appear multiple times <%@ page import=“java.util.*” %> contentType attribute e.g. “text/html” (the default for JSP’s) isThreadSafe attribute values are “true” (the default) or “false” if false, the servlet will implement SingleThreadModel

Page Directives (2) session attribute buffer attribute values are “true” (the default) or “false” if true the page uses HTTP sessions, creating one if it doesn’t already exist buffer attribute the size of the buffer in KB used by the out variable or “none” to turn off buffering autoflush attribute “true” (default) or “false” if true, the buffer will be flushed when it fills up if false, a buffer overflow exception may be raised

Page Directives (3) extends attribute info attribute the superclass of the generated servlet <%@ page extends=“package.class” %> caution: the server may already use a custom class info attribute a string that can be retrieved from the servlet with the getServletInfo method errorPage attribute URL of page to process any exceptions that are thrown and not caught on the current page The exception will be available on the error page through the exception variable.

Page Directives (4) isErrorPage attribute language attribute “true” or “false” (default) if true may act as error page for some other page language attribute only legal value is “java” (the default)

<%@ include file=“relativeURL” %> Include Directives <%@ include file=“relativeURL” %> The included file may be either static (*.html) or dynamic (*.jsp). The file is included when the JSP is translated into a servlet, i.e. when the page is first requested. When a dynamic file is included, it is the actual file itself (not its output) that is included. If an included file is modified, the modification dates of all files that include it must be updated!

Taglib Directives <%@ taglib uri=“tagLibURI” prefix=“tagPrefix” %> Introduces a tag library and defines a prefix for custom tags used on the page. More later

Alternative XML Directive Syntax <jsp:directive.directiveType attribute=“value” /> For example: <jsp:directive.page import=“java.util.*” />

Action Elements jsp:include jsp:forward jsp:useBean jsp:getProperty jsp:setProperty jsp:plugin

jsp:include <jsp:include page=“relativeURL” flush=“true” /> If the included page is dynamic (JSP or servlet) the output of the page rather than the page itself is included. The inclusion takes place each time the main page is requested. Two required parameters: page (the url of the included page) flush (must have the value “true”)

jsp:forward <jsp:forward page=“relativeURL” /> <jsp:param name=“pName” value=“pValue”> … </jsp:forward> Forwards the request to another page, optionally specifying additional parameters and values. The value of page may be an expression, so the value may be conditional (e.g. on the value of some parameter)

jsp:forward (2) <% String id = request.getParameter(“id”); String destination; if (id.startsWith(“a”)) destination = “adminLogin.jsp”; else destination = “userLogin.jsp”; %> <jsp:forward page=“<%= destination %>” />

JavaBeans A bean class must have a default (zero argument) constructor. A bean class may have properties and methods that can be accessed in JSP. A property is a private field with public get and set methods. A property xxx has accessor methods: public void setXxx(type x) public type getXxx() // if type is not boolean public type isXxx() // if type is boolean

jsp:useBean <jsp:useBean id=“name” class=“package.Class” /> The package or class needs to be imported in a page directive. Creates an object of the specified class and binds it to a variable with the specified id (unless a bean with that id already exists within the same scope). Optional scope attribute can be used to share beans with other JSP’s and servlets.

Bean scope scope=“page” (default) scope=“request” scope=“session” Bean is available only on the same page for the duration of the current request scope=“request” Bean is stored in the ServletRequest for the duration of the current request. Could include other pages (e.g. if the request is forwarded). scope=“session” Bean is stored in the HttpSession and is available to all servlets and JSP’s for the duration of the current session. scope=“application” Bean is stored in the ServletContext and is available to all servlets and JSP’s in the same webapp

Accessing bean properties <jsp:getProperty name=“beanID” property=“propertyName” /> <%= beanID.getPropertyName() %> <jsp:setProperty name=“beanID” property=“propertyName” value=“string” /> <% beanID.setPropertyName(“string”); %> If the property has a type other than String, jsp:setProperty will perform the type conversion.

Setting properties with parameters <jsp:setProperty name=“beanID” property=“propertyName” param=“paramName” /> If the parameter has the same name as the property, the param attribute may be omitted. Use “*” for property attribute to set all properties to values of identically named parameters.

Conditional bean initialization <jsp:useBean … > statements </jsp:useBean> The statements are executed only if a new bean was created, not if an existing bean is used. Useful if a bean is shared by several pages and it is unknown which page will be accessed first.

Using Tag Libraries <%@ taglib uri=“TLDUrl” prefix=“tagPrefix” %> The uri attribute gives the URL of a Tag Library Descriptor file for the tag library. The prefix attribute specifies a prefix to be used for tags defined in the library. <prefix:tagname … />

JSP Standard Tag Library (JSTL) JSTL has multiple tag library descriptors (TLDs) to clearly show the functional areas it covers and give each area its own namespace. The JSTL tag libraries come in two versions which differ only in the way they support the use of expressions for attribute values. In the JSTL-RT tag library, expressions are specified in the page's scripting language. In the JSTL-EL tag library, expressions are specified in the JSTL expression language

JSTL Expression Language Allows simplified syntax for accessing attributes: ${aName} instead of <%= pageContext.getAttribute("aName") %> ${aName.foo.bar} instead of <%= aName.getFoo().getBar() %> Allows easy access to application data without using scriptlets <c:if test="${sessionScope.cart.numberOfItems > 0}"> ... </c:if>

RT versus EL The RT library is usually better when the JSP page directly computes all values. The EL library is better when the JSP page uses only values computed by servlets (e.g. when using the MVC architecture). In between these extremes, it may be mostly a matter of taste.

Core JSTL Tags

XML JSTL Tags

Internationalization JSTL Tags

Database JSTL Tags

Flow Control Examples <c:if test=“${x < 5}”> … </c:if> <c:choose> <c:when test=“${x < 5}”> </c:when> <c:when test=“${x == 5}”> <c:otherwise> </c:otherwise> </c:choose>

Flow Control Examples (2) <table> <c:forEach var=“customer” items=“${customers}”> <tr><td><c:out value=“${customer}”/></td></tr> </c:forEach> </table>

Database Example <sql:setDataSource url=“jdbcURL” driver=“driverClassName” user=“username” password=“password” /> <sql:query var="customers"> SELECT * FROM customers WHERE country = ’China’ ORDER BY lastname </sql:query>

Database Example (2) <table> <c:forEach var="row" items="${customers.rows}"> <tr> <td><c:out value="${row.lastName}"/></td> <td><c:out value="${row.firstName}"/></td> <td><c:out value="${row.address}"/></td> </tr> </c:forEach> </table>

Defining Custom Tag Libraries Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to simpler form with custom tags than with beans. Custom tags are more work to setup than beans. Custom tags are not supported in JSP 1.0 but beans are.

Development Approaches Simple application or small team Place all Java directly in JSP or all HTML in servlet code. Call Java code in separate utility classes from scriptlets. Use Java Beans. Use custom tags. Use the MVC architecture. Complex application or large team

MVC Architecture Keep the model, the control, and the views separate. Model: Database and servlets that capture business logic. Control: Servlets that capture application logic. View: JSP’s that capture presentation logic. A servlet may respond to original request, look up or compute data, store results in beans and forward to JSP to present results.