Separating Programming and Presentation: JSP Technology WEB TECHNOLOGIES A COMPUTER SCIENCE PERSPECTIVE JEFFREY C. JACKSON Jackson, Web Technologies: A.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Introducing JavaScript
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.
The Web Warrior Guide to Web Design Technologies
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
DT228/3 Web Development JSP: Directives and Scripting elements.
Q: According to Intel, the Pentium conforms to the IEEE standards 754 and 854 for floating point arithmetic. If you fly in aircraft designed using a Pentium,
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems JavaServer Pages (JSP)
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.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 37 - JavaServer Pages (JSP): Bonus for Java Developers Outline 37.1 Introduction 37.2 JavaServer.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Separating Programming and Presentation: JSP Technology
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.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
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.
JSP Java Server Pages Softsmith Infotech.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
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)
 Embeds Java code  In HTML tags  When used well  Simple way to generate dynamic web-pages  When misused (complex embedded Java)  Terribly messy.
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.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
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.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
Chapter 6 Server-side Programming: Java Servlets
DAT602 Database Application Development Lecture 16 Java Server Pages Part 2.
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)
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.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
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.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
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.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
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.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Java Server Pages Yes it is Java. What you should know HTML Java.
World Wide Web has been created to share the text document across the world. In static web pages the requesting user has no ability to interact with the.
JSP Based on
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.
Java Servlets.
Scripted Page Web App Development (Java Server Pages)
Knowledge Byte In this section, you will learn about:
MSIS 655 Advanced Business Applications Programming
PHP.
Scripted Page Web Application Development (Java Server Pages)
Presentation transcript:

Separating Programming and Presentation: JSP Technology WEB TECHNOLOGIES A COMPUTER SCIENCE PERSPECTIVE JEFFREY C. JACKSON Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved

Get vs. Post Methods In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved What is JSP Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved What is JSP Technology The JavaServer Pages technology enables you to generate dynamic web content, such as HTML, DHTML, XHTML, and XML files, to include in a Web application. JSP files allow a Web server, such as Apache Tomcat, to add content dynamically to your HTML pages before they are sent to a requesting browser. When you deploy a JSP file to a Web server that provides a servlet engine, it is preprocessed into a servlet that runs on the Web server. This is in contrast with client-side JavaScript™ (within SCRIPT tags), which is run in a browser.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Why JSP? Servlet/CGI approach: server-side code is a program with HTML embedded JavaServer Pages (and PHP/ASP/ColdFusion) approach: server-side “code” is a document with program embedded – Supports cleaner separation of program logic from presentation – Facilitates division of labor between developers and designers

JSP vs. Servlet 6 JSPServlet JSP is a webpage scripting languageJSP is a webpage scripting language that can generate dynamic content. Servlets are Java programsServlets are Java programs that are already compiled which also creates dynamic web content JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets. Servlets run faster compared to JSP. It’s easier to code in JSP than in Java Servlets.Its little much code to write here. In MVC, jsp act as a view.In MVC, servlet act as a controller. JSP are generally preferred when there is not much processing of data required. servlets are best for use when there is more processing and manipulation involved. The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.custom tagsJava beans There is no such custom tag facility in servlets. JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc

Simple Hello World in JSP Hello World JSP Page. 7

Simple Hello World in Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println(" "); pw.println(" Hello World "); pw.println(" "); pw.println(" Hello World "); pw.println(" "); } 8

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Comments in JSP Two types

JSP by Example JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". Take the HTML file you used in the previous exercise. Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser. You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally. What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.) 10

JSP Expressions Put the following text in a file with.jsp extension (let us call it hello.jsp), place it in your JSP directory, and view it in a browser. Hello! The time is now Notice that each time you reload the page in the browser, it comes up with the current time. The character sequences enclose Java expressions, which are evaluated at run time. This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to user actions or vary from user to user. 11

JSP Scriptlets We have already seen how to embed Java expressions in JSP pages by putting them between the character sequences. But it is difficult to do much programming just by putting Java expressions inside HTML. JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between characters (just like expressions, but without the = sign at the start of the sequence.) 12

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Scriptlet A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can Declare variables or methods to use later in the file (see also Declaration). Write expressions valid in the page scripting language (see also Expression). Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Variable inside Scriptlets Variable declared inside declaration part is treated as a global variable. That means after conversion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class. If u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

JSP Scriptlets Here is a modified version of our JSP from previous section, adding in a scriptlet. <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now 15

JSP Scriptlets If you run the above example, you will notice the output from the "System.out.println" on the server log. This is a convenient way to do simple debugging (some servers also have techniques of debugging the JSP in the IDE. 16

JSP Scriptlets - out variable By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output. <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %> 17

JSP Scriptlets - request variable Another very useful pre-defined variable is "request". It is of type javax.servlet.http.HttpServletRequest A "request" in server-side processing refers to the transaction between a browser and the server. When someone clicks or enters a URL, the browser sends a "request" to the server for that URL, and shows the data returned. As a part of this "request", various data is available, including the file the browser wants from the server, and if the request is coming from pressing a SUBMIT button, the information the user has entered in the form fields. The JSP "request" variable is used to obtain information from the request as sent by the browser. For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.) 18

JSP Scriptlets - request variable <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% out.println( date ); out.println( " Your machine's address is " ); out.println( request.getRemoteHost()); %> 19

JSP Scriptlets - response variable A similar variable is "response". This can be used to affect the response being sent to the browser. For instance, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL. This response will actualy go all the way to the browser. The browser will then send a different request, to "anotherUrl". This is a little different from some other JSP mechanisms we will come across, for including another page or forwarding the browser to another page 20

JSP Directives We have been fully qualifying the java.util.Date in the examples in the previous sections. Perhaps you wondered why we don't just import java.util.*; It is possible to use "import" statements in JSPs, but the syntax is a little different from normal Java. Try the following example: <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now The first line in the above example is called a "directive". A JSP "directive" starts with characters. 21

JSP Directives The page directive can contain the list of all imported packages. To import more than one item, separate the package names by commas, e.g. There are a number of JSP directives, besides the page directive. Besides the page directives, the other most useful directives are include and taglib. The include directive is used to physically include the contents of another file. The included file can be HTML or JSP or anything else -- the result is as if the original JSP file actually contained the included text. To see this directive in action, create a new JSP Going to include hello.jsp... View this JSP in your browser, and you will see your original hello.jsp get included in the new JSP. 22

JSP Declarations The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions. To add a declaration, you must use the sequences to enclose your declarations, as shown below. <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now 23

JSP Tags Another important syntax element of JSP are tags. JSP tags do not use <%, but just the < character. A JSP tag is somewhat like an HTML tag. JSP tags can have a "start tag", a "tag body" and an "end tag". The start and end tag both use the tag name, enclosed in characters. The tag names have an embedded colon character : in them, the part before the colon describes the type of the tag. For instance: body If the tag does not require a body, the start and end can be conveniently merged together, as 24

JSP Tags Tags can be of two types: loaded from an external tag library, or predefined tags. Predefined tags start with jsp: characters. For instance, jsp:include is a predefined tag that is used to include other pages. We have already seen the include directive. jsp:include is similar. But instead of loading the text of the included file in the original file, it actually calls the included target at run-time (the way a browser would call the included target. In practice, this is actually a simulated request rather than a full round-trip between the browser and the server). Following is an example of jsp:include usage Going to include hello.jsp... 25

JSP Tags Try it and see what you get by changing the "jsp:include" to "jsp:forward" and see what is the difference. These two predefined tags are frequently very useful. 26

JSP Sessions On a typical web site, a visitor might visit several pages and perform several interactions. If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP. A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these. First we have a form, let us call it GetName.html 27

JSP Sessions What's your name? The target of the form is "SaveName.jsp", which saves the user's name in the session. Variable “session" is another variable that is normally made available in JSPs, just like out and request variables. 28

JSP Sessions <% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> Continue The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp. 29

JSP Sessions NextPage.jsp shows how to retrieve the saved name. Hello, If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of. The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded. 30

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JavaBeans Classes JSTL Core actions are designed to be used for simple, presentation-oriented programming tasks More sophisticated programming tasks should still be performed with a language such as Java JavaBeans technology allows a JSP document to call Java methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JavaBeans Classes Using a JavaBeans class in JSP

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JavaBeans Classes Using a JavaBeans class as shown: – Class must have a default (no-argument) constructor to be instantiated by useBean Automatically supplied by Java in this example – Class should belong to a package (avoids need for an import ) This class would go in WEB-INF/classes/my/ directory Instance of a JavaBeans class is a bean

JavaBeans Classes Simple property design patterns – Two types: getter and setter Both require that the method be public getter: – no arguments – returns a value – name begins with get (or is, if return type is boolean ) followed by upper case letter setter: – one argument (same type as setter return value) – void – name begins with set followed by upper case letter Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved

JavaBeans Classes Simple property design pattern methods associate bean properties with beans – Name of bean property obtained by removing get/is/set method prefix and following the rule: If remaining name begins with two or more upper case letters, bean property name is remaining name: setAValue()  AValue If remaining name begins with a single upper case letter, bean property name is remaining name with this letter converted to lower case: getWelcome()  welcome

JSP Beans Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy. The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields. For instance, let us modify our GetName.html to also collect address and age. 36

JSP Beans The new version of GetName.html is What's your name? What's your address? What's your age? 37

JSP Beans To collect this data, we define a Java class with fields "username", " " and "age" and we provide setter methods "setUsername", "set " and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is upper-cased. So if the field is " ", its "setter" method will be "set ". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public. 38

JSP Beans package user; public class UserData { String username; String ; int age; public void setUsername( String value ) { username = value; } public void set ( String value ) { = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String get () { return ; } public int getAge() { return age; } } 39

JSP Beans Now let us change "SaveName.jsp" to use a bean to collect the data. Continue All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! The useBean tag will look for an instance of the "user.UserData" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean! 40

JSP Beans Let us modify NextPage.jsp to retrieve the data from bean.. You entered Name: Age: 41

JSP Beans Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean. We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag. 42

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP and Servlets JSP documents are not executed directly – When a JSP document is first visited, Tomcat 1.Translates the JSP document to a servlet 2.Compiles the servlet – The servlet is executed Exceptions provide traceback information for the servlet, not the JSP – The servlets are stored under Tomcat work directory

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP and Servlets A JSP-generated servlet has a _jspService() method rather than doGet() or doPost() – This method begins by automatically creating a number of implicit object variables that can be accessed by scriptlets

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Web Applications A web application is a collection of resources that are used together to implement some web-based functionality Resources include – Components: servlets (including JSP-generated) – Other resources: HTML documents, style sheets, JavaScript, images, non-servlet Java classes, etc.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Web Applications Sharing data between components of a web application – Tomcat creates one ServletContext object per web application – Call to getServletContext() method of a servlet returns the associated ServletContext – ServletContext supports setAttribute() / getAttribute() methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Web Applications Within Tomcat, all of the files of a simple web app are placed in a directory under webapps – JSP documents can go in the directory itself – “Hidden” files--such as servlet class files--go under a WEB-INF subdirectory (more later) Once the web app files are all installed, use Tomcat Manager to deploy the app

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Web Applications There are four URL patterns (from high to low precedence) If no URL pattern matches, Tomcat treats path as a relative file name

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Web Applications Methods on request object for obtaining path information: – Example: /HelloCounter/visitor/test.jsp – getContextPath() : returns /HelloCounter – getServletPath() : returns /visitor – getPathInfo() : returns /test.jsp

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Expression Language (EL) ${visits+1} is an example of an EL expression embedded in a JSP document – ${…} is the syntax used in JSP documents to mark the contained string as an EL expression – An EL expression can occur In template data: evaluates to Java String As (part of) the value of certain JSP attributes: evaluates to data type that depends on context

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Expression Language (EL) EL literals: – true, false – decimal integer, floating point, scientific-notation numeric literals – strings (single- or double-quoted) – null

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Expression Language (EL) EL variable names: like Java – Can contain letters, digits, _, and $ – Must not begin with a digit – Must not be reserved:

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Expression Language (EL) EL operators: – Relational:, =, ==, != Or equivalents: lt, gt, le, ge, eq, ne – Logical: &&, ||, ! Or equivalents: and, or, not – Arithmetic: +, - (binary and unary), * /, % (or div, mod ) – empty : true if arg is null or empty string/array/ Map / Collection – Conditional: ? : – Array access: [ ] (or object notation) – Parentheses for grouping

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup Three types of markup elements: – Scripting Ex: scriptlet Inserts Java code into servlet – Directive Ex: directive.page Instructs JSP translator – Action Standard: provided by JSP itself Custom: provided by a tag library such as JSTL

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup Two JSPX directives – directive.page ; some attributes: contentType session : false to turn off use of session object errorPage : component that will generate response if an exception is thrown isErrorPage : true to access EL implicit exception object – directive.include : import well-formed XML

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup Common variables: – var Name of a scoped variable that is assigned to by the action Must be a string literal, not an EL expression – scope Specifies scope of scoped variable as one of the literals page, request, session, or application page default scope, unless otherwise specified

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup set action – Setting (and creating) a scoped variable – Setting/creating an element of Map Actually, this fails at run time in JWSDP 1.3 (which treats EL implicit object Map s as read-only) Map Key

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup remove action – Only attributes are var and scope – Removes reference to the specified scoped variable from the scope object

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup out action – Normally used to write a string to the out JSP implicit object – Automatically escapes all five XML special characters – If value is null output is empty string Override by declaring default attribute

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup url action – value attribute value is a URL to be written to the out JSP implicit object – URL’s beginning with / are assumed relative to context path – param elements can be used to define parameters that will be URL encoded

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup Alternative to the value attribute ( set and param elements) – If element has content, this is processed to produce a String used for value – Even out element will produce string, not write to the out object Assigns value of variable messy (XML escaped) to scoped variable clean

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup if action – General form includes scoped variable to receive test value The element can be empty if var is present Assigned Boolean value of test attribute

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup choose action Hi! Welcome back! You’re a regular!

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved JSP Markup forEach action – Used to increment a variable: – Used to iterate over a data structure:

JSP Markup forEach action – Can iterate over array, Map, Collection, Iterator, Enumeration – Elements of Map are Map.Entry, which support key and value EL properties:

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Tag Libraries Wouldn’t it be nicer to write the mortgage app as

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Tag Libraries

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Tag Libraries Place custom tag definition in a tag file having the name of the custom action – mortgage.tagx Place tag file in a tag library (e.g., directory containing tag files) – /WEB-INF/tags Add namespace declaration for tag library

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC Many web apps are based on the Model-View- Controller (MVC) architecture pattern Controller Model ComponentsView HTTP request HTTP response

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC Typical JSP implementation of MVC Controller (Java servlet) Model Components (beans, DBMS) View (JSP document) HTTP request HTTP response

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC Forwarding an HTTP request from a servlet to another component: – By URL – By name Ex: /HelloCounter.jspx

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC How does the controller know which component to forward to? – getPathInfo() value of URL’s can be used – Example: servlet mapping pattern in web.xml : URL ends with: getPathInfo() returns:

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC JSP include action Execute specified component and include its output in place of the include element

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved MVC Adding parameters to the request object seen by an included component: request object seen by navbar.jspx will include parameter named currentPage with value home