© Yaron Kanza Server-Side Programming using Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Slides:



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

Object-Oriented Enterprise Application Development JavaServer Pages.
Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 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.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
JSP – Java Server Pages Representation and Management of Data on the Internet.
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.
JSP – Java Server Pages Part 2 Representation and Management of Data on the Internet.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Servlet and JSP Programming: An Introduction Spiros Papadimitriou
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
1 JSP – Java Server Pages Representation and Management of Data on the Internet.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
JSP Java Server Pages Softsmith Infotech.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Introduction to Java Server Pages (JSPs) Robert Thornton.
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.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
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.
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:
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
1 (Server-Side Programming using Java Server Pages) cs
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
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.
Java Server Pages (JSP)
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Chapter 11 Invoking Java Code with JSP Scripting Elements.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
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.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
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.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
CSI 3125, Preliminaries, page 1 JSP (Java Server Pages)
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 (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
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.
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 Java Server Pages. Hello, !
Developing JavaServer Pages
Java Servlets.
JSP – Java Server Pages Part 1
Pre-assessment Questions
Invoking Java Code from JSP
JSP implicit objects & directive elements
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.
Presentation transcript:

© Yaron Kanza Server-Side Programming using Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher

Agenda Introduction to JSP JSP Life Cycle Basic JSP Elements Interacting with other Resources Links

Servlets allow us to write dynamic Web pages Easy access to request, session and context data Easy manipulation of the response (cookies, etc.) And lots more... It is very inconvenient to write and maintain long and mostly static HTML pages using Servlets (even though such pages are very common) out.println(" Bla Bla " + "bla bla bla bla" + "lots more here...") 3 Many HTML Pages are Mostly Static

The Idea: Use HTML for most of the page Write Servlet code directly in the HTML page, marked with special tags The server automatically translates a JSP page to a Servlet class and invokes this servlet In Tomcat, you can find the generated Servlet code under /work/Catalina/localhost/org/apache/jsp A JSP is no more than a convenient way to write Servlets that output textual data 4 Introducing JSP

Servlets: HTML code is printed using Java code JSP: Java code is embedded in HTML code Not only for HTML! JSP can be used for any textual format Servlets can be used for any data! Java HTML JAVA 5 Relationships

Hello World Hello World 6 JSP – Example

DEMO simpledate.jsp 7

8 The file dates.jsp is in C:\Apache Tomcat \webapps\examples\jsp\dates The file dates.jsp is in C:\Apache Tomcat \webapps\examples\jsp\dates The url The url JSP – Example (from Tomcat 7)

package org.apache.jsp.jsp.dates; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class date_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { … //some more auto generating initialization code public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; C:\Apache Tomcat \work\Catalina\localhost\examples\org\apache\jsp\jsp\dates\date_jsp.java Translation to Servlet 9

try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write(" \r\n"); out.write(" Hello World \r\n"); out.write(" \r\n"); out.write(" "); out.print( new java.util.Date() ); out.write(" \r\n"); out.write(" Hello World \r\n"); out.write(" \r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } 10

Apache Implementation Generated Servlet Sun Specifications classes interfaces Abstract class extended by every generated Servlet 11 Generated Servlet Hierarchy (Tomcat Implementation)

JSP Limitations and Advantages JSP can only do what a Servlet can do Easier to write and maintain HTML Easier to separate HTML from code Can be created using a "reverse engineering technique": Create static HTML and then replace static data with Java code 12

Agenda Introduction to JSP JSP Life Cycle Basic JSP Elements Interacting with other Resources Links

Written by Marty Hall. Core Servlets & JSP book: Request #1 Request #2 Request #3 Request #4 Request #5 Request #6 JSP page translated into servlet YesNo YesNo JSP’s Servlet compiled YesNo YesNo Servlet instantiated and loaded into server's memory YesNoYesNoYesNo init (or equivalent) called YesNoYesNoYesNo doGet (or equivalent) called Yes Page first written Server restarted Page modified 14 JSP Life Cycle Translation & compilation only after first call…

When the JSP file is modified, it is translated into a Servlet But only after the JSP’s URL is requested by a client The application is not necessarily reloaded immediately when the JSP file is modified The server does not generate the Servlet class after startup, if the class already exists and is not too old The generated servlet can handle GET, POST, HEAD requests though it does not implement doGet(), doPost(), doHead() explicitly Its Servlet.service() method calls the newly implemented main method named HttpJspBase._jspService() 15 JSP Translation JSP file named file.jsp will be translated into the Java file file_jsp.java

init() and destroy() init() of the generated Servlet is called every time the Servlet class is loaded into memory and instantiated destroy() of the generated Servlet is called every time the generated Servlet is removed init() and destroy() are called even when the reason for loading is a modification of the JSP file 16

In JSP pages, as in regular Servlets, sometimes we want to implement init and destroy It is illegal to use JSP declarations to override init or destroy, since they are (usually) already implemented by the generated Servlet Instead, override the methods jspInit() and jspDestroy() The generated servlet is guaranteed to call these methods from init and destroy, respectively The standard versions of jspInit and jspDestroy are empty (placeholders for you to override) 17 jspInit and jspDestroy

Thread Synchronization After the Servlet is generated, one instance of it serves requests in different threads, just like any other Servlet In particular, the service method (_jspService) may be executed by several concurrent threads Thus, as with Servlets, JSP programming requires handling concurrency 18

Agenda Introduction to JSP JSP Life Cycle Basic JSP Elements Interacting with other Resources Links

HTML code: content JSP Comments: Expressions: Scriptlets (statements): Declarations: Directives: Actions:, Expression-Language Expressions: ${expression} 20 Basic Elements in a JSP File

A JSP expression is being used to insert Java values directly into the output It has the form:, where expression can be a Java object, a numerical expression, a method call that returns a value, etc... For example: The heading space and the following space are not created in the result. Use “ “ if you want a real space 21 JSP Expressions

JSP Expressions – cont. Within the generated Java code A JSP Expression is evaluated The result is converted to a string The string is inserted into the page This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request, the session, etc... 22

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {... response.setContentType("text/html");... out.write(" A Random Number \r\n"); out.print( Math.random() ); out.write("\r\n");... } The generated servlet calls out.write() for Strings, and out.print() for objects Default content-type Expression Translation A Random Number 23

Predefined Variables (Implicit Objects) The following predefined variables can be used: request: the HttpServletRequest response: the HttpServletResponse session: the HttpSession associated with the request out: the PrintWriter (a buffered version of type JspWriter) used to fill the response content application: The ServletContext config: The ServletConfig 24

Predefined Variables - Example 25 JSP Expressions JSP Expressions Current time: Your hostname: Your session ID: The testParam form parameter:

26 Predefined Variables - Example

JSP Scriplets (Statements) JSP Scriptlets let you insert arbitrary code into the Servlet service method ( _jspService ) Scriptlets have the form: The code is inserted verbatim into the service method, according to the location of the scriptlet Scriptlets have access to the same automatically defined variables as expressions 27

28 public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... response.setContentType("text/html");... out.print(foo()); bar();... } Scriptlet Translation

You won the game! You lost the game! if (Math.random() < 0.5) { out.write("You won the game!"); } else { out.write("You lost the game!"); } 29 A Divided-Code Example Scriptlets do not have to be continuous

DEMO expressions.jsp 30

A JSP declaration lets you define methods or members that are being inserted into the Servlet class (outside of all methods) It has the following form: For example: JSPs are intended to contain a minimal amount of code so it is usually of better design to define methods in a separate Java class JSP Declarations

Declaration Example Print the number of times the current page has been requested since the Servlet initialization: <%! private synchronized int incAccess() { return ++accessCount; } %> Accesses to page since Servlet init: 32

Declaration Example – cont. public class serviceCount_jsp extends... implements... throws... { private int accessCount = 0; private synchronized int incAccess() { return ++accessCount; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... out.write(" Accesses to page since Servlet init: "); out.print(incAccess());... }... } Generated Servlet Java permits variable initialization on declaration, even if the location is outside any method’s scope 33

JSP Directives A JSP directive affects the structure of the Servlet class that is generated from the JSP page It usually has the following form: Three important directives: page, include and taglib 34

import attribute: A comma separated list of classes/packages to import contentType attribute: Sets the MIME-Type of the resulting document (default is text/html) 35 page-Directive Attributes

What is the difference between setting the page contentType attribute, and writing ? In the latter case, the new servlet will call response.setContentType() twice The first, impicit (from the JSP point of view), call will be with the default content type. The second, explicit, call might even come after the buffer was flushed or after the writer was obtained… 36 page-Directive Attributes – cont.

session="true|false" specifies if to use a session? buffer="sizekb|none|8kb" Specifies the content-buffer (out) size in kilo-bytes autoFlush="true|false" Specifies whether the buffer should be flushed when it fills, or throw an exception otherwise isELIgnored ="true|false" Specifies whether JSP expression language is used The underlined values are the defaults 37 page-Directive Attributes – cont.

Agenda Introduction to JSP JSP Life Cycle Basic JSP Elements Interacting with other Resources Links

JSP Cooperation We will consider several ways in which JSP and other resources cooperate Forwarding the request handling to other resources Including the content of other sources Including the code of other JSP files Forwarding exception handling to other JSPs 39

Actions JSP actions use constructs in XML syntax to control the behavior of the Servlet engine Using actions, you can forward the request to another resource in the application dynamically include a resource content in the response Forward and include are translated to an invocation of the RequestDispatcher 40

jsp:forward - Forwards the requester to a new resource }"> <jsp:param name="parameterName" value="{parameterValue | }" /> * You can use %=, % instead of so that the code would be a legal XML 0 or more parameters (not attributes!) added to the original request parameters 41 The Forward Action

Forward Action Example – forward.jsp 42 " /> " />

Print Request Params : 43 Forward Action Example – requestParams.jsp

jsp:include - Include a resource content at run time }"> <jsp:param name="parameterName" value="{parameterValue | }" />* 0 or more parameters added to the original request parameters 44 The Include Action

DEMO forward 45

Include (action) Example Included part begins: " /> Included part ends 46 Include Action Example – include.jsp

: requestParams2.jsp is different from requestParams.jsp in not having the preceding and following html tags (otherwise the output HTML code would have, and duplicated) 47 Include Action Example – requestParams2.jsp

This directive lets you include files at the time the JSP page is translated into a Servlet The directive looks like this: Included JSP content can affect main JSP page e.g. included page directive can affect the result ContentType Generated Servlets are updated when included files change 48 The Include Directive

DEMO include 49

Include Action File1.jsp Servlet1 File2.jsp Servlet2 HTML content HTML content HTML content Using RequestDispatcher Main JSP 50

Include Directive File1.jsp File2.jsp Servlet HTML content 51

Include Action vs. Directive When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime (so the resource needs not be a JSP or even a Servlet) When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation (so the included resource must have JSP syntax) 52

Include Action vs. Directive - Example Including JSP Here is an interesting page. Bla, Bla, Bla, Bla. blabla.jsp Accesses to page since Servlet init: accessCount.jsp Page Created for Simpsons at. here. myMail.jsp 53

out.write(" \r\n"); out.write(" Including JSP \r\n"); out.write(" \r\n"); out.write(" Here is an interesting page. \r\n"); out.write(" Bla, Bla, Bla, Bla. \r\n"); out.write(" \r\n"); out.write(" Accesses to page since Servlet init: \r\n"); out.print( ++accessCount ); out.write(" \r\n"); org.apache.jasper.runtime.JspRuntimeLibrary. include(request, response, "/mymail.jsp", out, false); out.write(" \r\n"); BlaBla_jsp.java Original JSP Included JSP Similar to RequestDispatcher().include() Original JSP Include Action vs. Directive - Example 54

DEMO include-directive 55

We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives The default behaviour is displaying a 500 Internal Server Error with a partial stack trace with other exception info to the client (ugly and a security risk) You can log the entire stack trace along with other data for easier debugging Runtime exceptions or other exceptions which are declared as thrown by methods your JSP code use. Other exceptions cannot be thrown or else your generated servlet code wouldn’t compile 56 Error Pages

Defines a JSP page that handles uncaught exceptions The page in url should have true in the page-directive: The variable exception holds the exception thrown by the calling JSP Creating an error page without isErrorPage=true, is legal but the exception object is not created in the generated Servlet. If you refer to exception in such a JSP, you’ll have a compilation error… 57 Error Pages – cont.

Reading From Database <% Class.forName(“com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection (“jdbc:mysql:// “homer“, “doughnuts”); %> Can Connect!! connect.jsp Error Pages - Example 58

Connection Error Oops. There was an error when you accessed the database. Here is the stack trace: errorPage.jsp Error Pages – Example cont. 59

DEMO error-page 60

Agenda Introduction to JSP JSP Life Cycle Basic JSP Elements Interacting with other Resources Links

JSP Tutorial: Advanced Tutorials: JSP API: JSP Syntax Reference: 62