JSP – Java Server Pages Representation and Management of Data on the Internet.

Slides:



Advertisements
Similar presentations
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
Advertisements

© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
 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.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
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.
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.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
© Yaron Kanza Server-Side Programming using Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
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.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
JSP Java Server Pages Softsmith Infotech.
Introduction to Java Server Pages (JSPs) Robert Thornton.
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.
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:
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.
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
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.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
1 JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
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.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Chapter 11 Invoking Java Code with JSP Scripting Elements.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
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.
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.
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.
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.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
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.
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 Java Server Pages. Hello, !
JSP (Java Server Page) JSP is server side technology which is used to create dynamic web pages just like Servlet technology. This is mainly used for implementing.
Developing JavaServer Pages
COMP9321 Web Application Engineering Semester 2, 2017
Scripted Page Web App Development (Java Server Pages)
Invoking Java Code from JSP
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:

JSP – Java Server Pages Representation and Management of Data on the Internet

Introduction

What is JSP Good For? 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 not convenient to write and maintain long static HTML using Servlets out.println(" Bla Bla " + "bla bla bla bla" + "lots more here...")

JSP 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 the latter is actually invoked -In Tomcat 5.0 you can find the generated Servlet code under $CATALINA_BASE/work/

Relationships Servlets: HTML code is printed from Java code JSP: Java code is embedded in HTML code Java HTML Java HTML

Example Hello World Hello World Tomcat 5.0 Generated Servlet

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 use a "reverse engineering technique": create static HTML and then replace static data with Java code

Basic JSP Elements

Elements in a JSP file HTML code: content HTML comment: JSP Comment: Expressions: Scriptlets: Declarations: Directives: Actions: discussed later

JSP Expressions A JSP expression is 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:

JSP Expressions 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...

Expression Translation A Random Number 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");... }

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 These variables and more will be discussed in details

JSP Expressions JSP Expressions Current time: Your hostname: Your session ID: The testParam form parameter:

JSP Scriplets 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 scriplet Scriptlets have access to the same automatically defined variables as expressions

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

An Interesting Example Scriptlets don't have to be complete code blocks: 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!"); }

JSP Declarations A JSP declaration lets you define methods or members that get inserted into the Servlet class (outside of all methods) It has the following form: For example: It is usually of better design to define methods in a separate Java class...

Declaration Example Print the number of times the current page has been requested since the server booted (or the Servlet class was changed and reloaded): <%! private synchronized int incAccess() { return ++accessCount; } %> Accesses to page since server reboot:

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 server reboot: "); out.print(incAccess());... }... }

jspInit and jspDestroy In JSP pages, like regular Servlets, sometimes want to use init and destroy It is illegal to use JSP declarations to override init or destroy, since they (usually) are 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)

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: Multiple attribute settings for a single directive can be combined: Two types discussed in this section: page and include

page -Directive Attributes 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) Note that instead of using the contentType attribute, you can write

More page -Directive Attributes session="true|false" - use a session? buffer="sizekb|none" - Specifies the content-buffer size ( out ) errorPage="url " -Defines a JSP page that handles uncaught exceptions -The page in url must have true in the page-directive: isErrorPage="true|false" -The variable exception holds the exception thrown by the calling JSP

Reading From Database <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:" + Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from a"); ResultSetMetaData md = rs.getMetaData(); int col = md.getColumnCount(); %> showTableA.jsp

Reading From Database Oops. There was an error when you accessed the database. Here is the stack trace: errorPage.jsp

Table A exists!

Table A does not exist!

The include Directive This directive lets you include files at the time the JSP page is translated into a Servlet The directive looks like this: JSP content can affect main page In Tomcat 5.x, generated Servlet is updated when included files change (unlike old versions...)

Including JSP Here is an interesting page. Bla, Bla, Bla, Bla. BlaBla.jsp Page Created for Dbi Course. us here. Accesses to page since server reboot: AccessCount.jsp

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("Page Created for Dbi Course. us \r\n"); out.write(" here.\r\n"); out.write(" \r\n"); out.write("Accesses to page since server reboot: \r\n"); out.print( ++accessCount ); out.write("\r\n"); out.write(" ");

Writing JSP in XML (and vice versa) We can replace the JSP tags with XML tags that represent -Expressions -Scriptlets -Declarations -Directives

Expression Code Declaration <jsp:directive.type Attribute="value"/>

for(int i=1; i<=10; ++i) { i }

Variables in JSP

Implicit Objects As seen before, some useful variables, like request and session are predefined These variables are called implicit objects Implicit objects are defined in the scope of the service method -Can these be used in JSP declarations? Implicit objects are part of the JSP specifications

The objects request and response request and response are the HttpServletRequest and HttpServletResponse arguments of the service method Using these objects, you can: Read request parameters Set response headers etc. (everything we learned in Servlet lectures)

The object out This is the Writer used to add write output into the response body This object implements the interface JspWriter, which supports auto-flush Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute of the page directive

The object page Simply a synonym for (Object)this page is not very useful in JSP pages It was created as a placeholder for the time when the scripting language could be something other than Java

The object pageContext pageContext is a new object introduced by JSP This object encapsulates use of server-specific features (e.g. higher performance JspWriters) Access server-specific features through this class rather than directly, so your code will conform to JSP spec. and not be server dependent This object is also used to store page-scoped Java Beans (discussed later)

The object session This is the HttpSession object associated with the request If the session attribute in the page directive is turned off ( ) then this object is not available Recall that a session is created by default

The object config This is the ServletConfig of the page, as received in the init() method Remember: Contains Servlet specific initialization parameters Later, we will study how initialization parameters are passed to JSP pages in Tomcat You can get the ServletContext from config

The object application This is the ServletContext as obtained via getServletConfig().getContext() Remember: -The ServletContext is shared by all Web-application Servlets (including ones generated from JSP) -Getting and setting attributes is with getAttribute and setAttribute of ServletContext -You can use this object to get application-wide initialization parameters

Review: Variable Scope

Servlet Package and Helper Classes The generated Servlet has a named package In Tomcat, this package is: org.apache.jsp In Java, you cannot use classes from the default package (i.e. with no package declaration) from a named package! Therefore, helper classes used by JSP pages must have a named package

JSP Actions

Actions JSP actions use constructs in XML syntax to control the behavior of the Servlet engine Using actions, you can -dynamically insert a resource content -forward the user to another page -reuse Java Beans and custom tags - briefly discussed later

The forward Action jsp:forward - Forwards the requester to a new resource }"> <jsp:param name="parameterName" value="{parameterValue | }" /> * This action is translated to an invocation of the RequestDispatcher

The include Action jsp:include - Include a resource content at run time }" flush="true| false" > <jsp:param name="parameterName" value="{parameterValue | }" />* This action is also translated to an invocation of the RequestDispatcher

include Directive vs. Action When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime Question: using which of the latter options can the included element change the HTTP headers or status?

JSP Life Cycle

The following table describes the life cycle of JSP generated Servlet in details:

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

JSP Translation When the JSP file is modified, JSP is translated into a Servlet -Application need not be reloaded when JSP file is modified -In Tomcat 5.0, translation is done even if included files (through the include directive) are modified Server does not generate the Servlet class after startup, if the latter already exists -Generated Servlet acts just like any other Servlet

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 The latter two happen even if the reason is modification of the JSP file

Thread Synchronization After the Servlet is generated, one instance of it services requests in different threads, just like any other Servlet In particular, the service method (_jspService) may be executed by several concurrent threads Thus, like Servlets, JSP code should deal with concurrency

JSP in Tomcat 5.0

Tomcat 5.0 Generated Servlet Hello World Hello World Tomcat 5.0 Generated Servlet

Generated Servlet Hierarchy (Tomcat 5.0 Implementation) Apache Implementation Generated Servlet Sun Specifications different packages

Implementation vs. Specification JSP files should conform to JSP specifications and be container independent For example, JSP files that assume extension of HttpServlet will compile and run correctly under Tomcat, but may fail to compile under other containers The implicit object pageContext exists for this reason

JSP Initial Parameters Like Servlets, initial parameters can be passed to JSP files using the element of the application configuration file web.xml Use the sub-element instead of the sub-element A is also needed -Use the JSP file as the

dbLogin snoopy dbPassword snoopass

ParamPage /paramPage.jsp tableName users ParamPage /initParam.jsp

JSP initial parameters Hello I should use the table <%= config.getInitParameter("tableName") %>. To access the Database, I should use the login <%= application.getInitParameter("dbLogin") %> and the password <%= application.getInitParameter("dbPassword") %>.

Appendix 1: Java Beans in JSP

Motivation Software components (e.g. objects, data structures, primitives) are extensively used in Web applications For example: -Service local variables -Attributes forwarded in requests -Session attributes, like users information -Application attributes, like access counters

Motivation Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies...)

Java Beans: The Idea Wrap your data, in a standard fashion, inside a Java class (Java Bean) Use special JSP actions to access and manipulate the bean Use special action attributes to specify the properties of the bean, like its scope

Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages

package dbi; public class CounterBean { private int counter; public CounterBean() { counter = 0; } public int getCounter() { return counter; } public void setCounter(int i) { counter = i; } public void increment() { ++counter; } } Bean must reside in a package Bean is created by an empty constructor getCounter and setCounter define the property counter other methods can be used

<jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> Welcome to Page A Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> Page B pageA.jsp invokes getCounter()

<jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> Welcome to Page B Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> Page A pageB.jsp

Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session

package dbi; public class UserInfoBean { private String firstName; private String lastName; public UserInfoBean() { firstName = lastName = null;} public String getFirstName() {return firstName;} public String getLastName() {return lastName;} public void setFirstName(String string) {firstName = string;} public void setLastName(String string) {lastName = string;} }

User Info Fill in your details: Your First Name: <INPUT TYPE="text" NAME="firstName"> Your Last Name: <INPUT TYPE="text" NAME="lastName"> infoForm.html

<jsp:useBean id="userInfo" class="dbi.UserInfoBean" scope="session"/> <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, Have a nice session! User Info B infoA.jsp Match parameters to corresponding properties

<jsp:useBean id="userInfo" class="dbi.UserInfoBean" scope="session"/> <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, Have a nice session! User Info A infoB.jsp

Advantages of Java Beans Easy and standard management of data -Automatic management of bean sharing and lots more Good programming style -Allow standard but not direct access to members -You can add code to the setters and getters (e.g. constraint checks) without changing the client code -You can change the internal representation of the data without changing the client code Increase of separation between business logic (written by programmers) and HTML (written by GUI artists)

Appendix 2: Custom JSP Tags

Custom JSP Tags JSP code may use custom tags - tags that are defined and implemented by the programmer The programmer defines how each of the custom tags is translated into Java code There are two methods to define custom tags: -Tag libraries - used in old versions of JSP -Tag files - much simpler, introduced in JSP 2.0

Tag Libraries A tag library consists of: -Tag handlers - Java classes that define how each of the new tags is translated into Java code -A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag

A Simple TagLib Example package dbi; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class DateTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); } DateTag.java

1.0 date dbi.DateTag empty dbi-taglib.tld taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib.tld" %> Hello. The time is: taglibuse.jsp

Tag Files The new version of JSP (2.0) provides an extremely simplified way of defining tags The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code This way, the programmer can avoid creating tag handlers and TLD files

date.tag Hello. The time is: taguse.jsp The Simplified Example

Other Capabilities of Custom Tags Attributes -You can define the possible attributes of the Tags -These can be accessed during the Tag translation Tag Body -Tag translation may choose to ignore, include or change the tag body