1 Processing phase Translation phase JSP page translation and processing phases Client Server Request Response Hello.jsp helloServlet.class helloServlet.java.

Slides:



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

CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
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.
The JSP Directives Vijayan Sugumaran School of Business Administration Oakland University Parts of this lecture provided by Coreservlets.com.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
Introduction to JavaServer Pages Vijayan Sugumaran Dept. of DIS Oakland University Parts of this presentation was provided by
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.
Web Application: Java Server Pages (JSP) INE2720 Web Application Software Development Essential Materials.
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.
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.
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.
JSP Java Server Pages Softsmith Infotech.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
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.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
1 JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
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.
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.
Web Application: Java Server Pages (JSP) THETOPPERSWAY.COM.
SKT-SSU IT Training Center Servlet and JSP. Chapter Eleven: Invoking Java Code with JSP Scripting Elements.
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.
JSP in Action. JSP Standard Actions forward, include, useBean, setProperty, getProperty, text, element, and plugin Additional actions param, params,
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.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Introduction to Server-Side Web JavaBeans; basic concepts and syntax.
Developing JavaServer Pages
Java Server Pages By: Tejashri Udavant..
Scripted Page Web App Development (Java Server Pages)
USING JAVABEANS COMPONENTS IN JSP DOCUMENTS K. Phani Sirisha
Pre-assessment Questions
Invoking Java Code from JSP
COSC 2956 Internet Tools Java Server Pages.
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.
Web Technologies Java Beans & JSP
Presentation transcript:

1 Processing phase Translation phase JSP page translation and processing phases Client Server Request Response Hello.jsp helloServlet.class helloServlet.java Read Generate Execute

2 Template Pages Server Page Template <html><title> A simple example </title> The time now is </body></html> Resulting HTML <html><title> A simple example </title> The time now is Tue Nov 5 16:15:11 PST 2002 </body></html> translation

3 Dividing Pure Servlets Public class MySelect { public void doGet(…){ public void doGet(…){ if (isValid(..){ if (isValid(..){ saveRecord(); saveRecord(); out.println(“ ”); out.println(“ ”); …. …. } } private void isValid(…){…} private void isValid(…){…} private void saveRecord(…) {…} private void saveRecord(…) {…}} Servlet JSP JavaBeans Process request Presentation Business logic controller view model Model-View-Controller (MVC) design

4 JSP Components There are three main types of JSP constructs that you embed in a page. There are three main types of JSP constructs that you embed in a page. –Scripting elements You can specify Java code You can specify Java code Expressions, Scriptlets, Declarations Expressions, Scriptlets, Declarations –Directives Let you control the overall structure of the servlet Let you control the overall structure of the servlet Page, include, Tag library Page, include, Tag library –Actions Enable the use of server side Javabeans Enable the use of server side Javabeans Transfer control between pages Transfer control between pages

5 Types of Scripting Elements You can insert code into the servlet that will be generated from the JSP page. You can insert code into the servlet that will be generated from the JSP page. Expressions: Expressions: –Evaluated and inserted into the servlet ’ s output. i.e., results in something like out.println(expression) Scriptlets: Scriptlets: –Inserted verbatim into the servlet ’ s _jspService method (called by service) Declarations: Declarations: –Inserted verbatim into the body of the servlet class, outside of any existing methods

6 JSP Expressions Format Format – – Result Result –Expression evaluated, converted to String, and placed into HTML page at the place it occurred in JSP page –That is, expression placed in _jspService inside out.print Examples Examples –Current time: –Current time: –Your hostname: –Your hostname: XML-compatible syntax XML-compatible syntax – Java Expression – Java Expression –XML version not supported by Tomcat 3. Until JSP 1.2, servers are not required to support it.

7 JSP/Servlet Correspondence Original JSP Original JSP A Random Number A Random Number Possible resulting servlet code Possible resulting servlet code public void _jspService(HttpServletRequest request, public void _jspService(HttpServletRequest request, HttpServletResponse response) HttpServletResponse response) throws ServletException, IOException { throws ServletException, IOException { request.setContentType("text/html"); request.setContentType("text/html"); HttpSession session = request.getSession(true); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); JspWriter out = response.getWriter(); out.println(" A Random Number "); out.println(" A Random Number "); out.println(Math.random()); out.println(Math.random()); }

8 Example Using JSP Expressions <BODY> JSP Expressions JSP Expressions <UL> Current time: Current time: Your hostname: Your hostname: Your session ID: Your session ID: The testParam form parameter: The testParam form parameter: </UL></BODY>

9 Predefined Variables (Implicit Objects) They are created automatically when a web server processes a JSP page. They are created automatically when a web server processes a JSP page. request: The HttpServletRequest (1st arg to doGet) request: The HttpServletRequest (1st arg to doGet) response: The HttpServletResponse (2nd arg to doGet) response: The HttpServletResponse (2nd arg to doGet) session session –The HttpSession associated with the request (unless disabled with the session attribute of the page directive) out out –The stream (of type JspWriter) used to send output to the client application application –The ServletContext (for sharing data) as obtained via getServletConfig().getContext(). page, pageContext, config, exception page, pageContext, config, exception

10 Implicit objects – Class files application: javax.servlet.ServletContext application: javax.servlet.ServletContext config: javax.servlet.ServletConfig config: javax.servlet.ServletConfig exception: java.lang.Throwable exception: java.lang.Throwable out: javax.servlet.jsp.JspWriter out: javax.servlet.jsp.JspWriter page: java.lang.Object page: java.lang.Object pageContext: javax.servlet.jsp.PageContext pageContext: javax.servlet.jsp.PageContext request: javax.servlet.ServletRequest request: javax.servlet.ServletRequest response: javax.servlet.ServletResponse response: javax.servlet.ServletResponse session: javax.servlet.http.HttpSession session: javax.servlet.http.HttpSession

11 Access Client Information The getRemoteHost method of the request object allows a JSP to retrieve the name of a client computer. The getRemoteHost method of the request object allows a JSP to retrieve the name of a client computer. Your Information Your Information Your computer's IP address is Your computer's name is Your computer's name is Your computer is accessing port number Your computer is accessing port number

12 Work with the Buffer When the page is being processed, the data is stored in the buffer instead of being directly sent to the client browser. When the page is being processed, the data is stored in the buffer instead of being directly sent to the client browser. This is a test of the buffer This is a test of the buffer <%out.flush(); for (int x=0; x < ; x++); out.print("This test is generated about 5 seconds later."); out.flush();%>

13 Working with Session object The session object has many useful methods that can alter or obtain information about the current session. The session object has many useful methods that can alter or obtain information about the current session. –setMaxInactiveInterval(second) Session Values Session Values <%session.setMaxInactiveInterval(10); String name = (String) session.getAttribute("username"); out.print("Welcome to my site " + name + " "); %>

14 JSP Scriptlets Format: Format: Result Result –Code is inserted verbatim into servlet's _jspService Example Example – – XML-compatible syntax XML-compatible syntax – Java Code – Java Code

15 JSP/Servlet Correspondence Original JSP Original JSP Possible resulting servlet code Possible resulting servlet code public void _jspService(HttpServletRequest request, public void _jspService(HttpServletRequest request, HttpServletResponse response) HttpServletResponse response) throws ServletException, IOException { throws ServletException, IOException { request.setContentType("text/html"); request.setContentType("text/html"); HttpSession session = request.getSession(true); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); JspWriter out = response.getWriter(); out.println(foo()); out.println(foo()); bar(); bar(); }

16 JSP Scriptlets Example <% for (int i=100; i>=0; i--) {%> bottles of beer on the wall. bottles of beer on the wall. <%}%>

17 Example Using JSP Scriptlets <HTML><HEAD> Color Testing Color Testing </HEAD><% String bgColor = request.getParameter("bgColor"); request.getParameter("bgColor"); boolean hasExplicitColor; if (bgColor != null) { hasExplicitColor = true; hasExplicitColor = true; } else { hasExplicitColor = false; hasExplicitColor = false; bgColor = "WHITE"; bgColor = "WHITE";}%> "> ">

18 JSP Declarations Format Format – – Result Result –Code is inserted verbatim into servlet's class definition, outside of any existing methods Examples Examples – – XML-compatible syntax XML-compatible syntax – Java Code – Java Code

19 Original JSP Original JSP Some Heading Some Heading <%! private String randomHeading() { private String randomHeading() { return(" " + Math.random() + " "); return(" " + Math.random() + " "); }%> Possible resulting servlet code Possible resulting servlet code public class xxxx implements HttpJspPage { private String randomHeading() { private String randomHeading() { return(" " + Math.random() + " "); return(" " + Math.random() + " "); } public void _jspService(HttpServletRequest request, public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); request.setContentType("text/html"); HttpSession session = request.getSession(true); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); JspWriter out = response.getWriter(); out.println(" Some Heading "); out.println(" Some Heading "); out.println(randomHeading()); out.println(randomHeading()); } JSP/Servlet Correspondence

20 Example Using JSP Declarations …<body> JSP Declarations JSP Declarations Accesses to page since server reboot: Accesses to page since server reboot: </body></html> After 15 total visits by an arbitrary number of different clients After 15 total visits by an arbitrary number of different clients

21 JSP Tags + HTML Tags Table of Square Roots Table of Square Roots Number Number Square Root Square Root <% <% for (int n=0; n<=100; n++) for (int n=0; n<=100; n++) { %> %> <% <% } %> %>

22 JSP Directives Affect the overall structure of the servlet Affect the overall structure of the servlet Two possible forms for directives Two possible forms for directives – – directive attribute1= “ value1 ” attribute2= “ value2 ” attribute2= “ value2 ” …. …. attributeN= “ valueN ” %> attributeN= “ valueN ” %> There are three types of directives There are three types of directives –Page, include, and taglib

23 Purpose of the page Directive Give high-level information about the servlet that will result from the JSP page Give high-level information about the servlet that will result from the JSP page Can control Can control –Which classes are imported –What class the servlet extends –What MIME type is generated –How multithreading is handled –If the servlet participates in sessions –The size and behavior of the output buffer –What page handles unexpected errors

24 The import Attribute Format Format – – Purpose Purpose –Generate import statements at top of servlet Notes Notes –Although JSP pages can be almost anywhere on server, classes used by JSP pages must be in normal servlet dirs

25... The import Attribute The import Attribute <%! private String randomID() { int num = (int)(Math.random()* ); int num = (int)(Math.random()* ); return("id" + num); return("id" + num);} private final String NO_VALUE = " No Value "; %><% Cookie[] cookies = request.getCookies(); String oldID = ServletUtilities.getCookieValue(cookies, "userID", NO_VALUE); String newID; if (oldID.equals(NO_VALUE)) { newID = randomID(); } else { newID = oldID; } LongLivedCookie cookie = new LongLivedCookie("userID", newID); response.addCookie(cookie);%> This page was accessed at with a userID cookie of. Example of import Attribute

26 Example of import Attribute First access First access Subsequent accesses Subsequent accesses

27 The contentType Attribute Format Format – – Purpose Purpose –Specify the MIME type of the page generated by the servlet that results from the JSP page

28 First Last Address Marty Hall Larry Brown Bill Gates Larry Ellison Generating Excel Spreadsheets

29 page errorPage="orderError.jsp" import="java.text.NumberFormat" %> import="java.text.NumberFormat" %> Your order: Your order: <% String numTees = request.getParameter("t-shirts"); String numTees = request.getParameter("t-shirts"); String numHats = request.getParameter("hats"); String numHats = request.getParameter("hats"); NumberFormat currency = NumberFormat.getCurrencyInstance(); NumberFormat currency = NumberFormat.getCurrencyInstance();%> Number of tees: Your price: Number of hats: Your price: Order Form Order Form What would you like to purchase? What would you like to purchase? Item Item Quantity Quantity Unit Price Unit Price … Form Processing

30 JSP Actions There are seven standard JSP actions. There are seven standard JSP actions. –Include, param, forward, plugin, … –Include action is similar to include directive. –You can add additional parameters to the existing request by using the param action. –The plugin action inserts object and embed tags (such as an applet) into the response to the client. –In the coming slides, we will talk about “ include ” and “ plugin ” actions.

31 Including Pages at Request Time Format Format – – Purpose Purpose –To reuse JSP, HTML, or plain text content –JSP content cannot affect main page: only output of included JSP page is used –To permit updates to the included content without changing the main JSP page(s)

32 Including Pages: Example Code...<BODY> What's New at JspNews.com What's New at JspNews.com <P> Here is a summary of our three most recent news stories: <OL> </OL></BODY></HTML>

33 Background: What Are Beans? Classes that follow certain conventions Classes that follow certain conventions –Must have a zero-argument (empty) constructor –Should have no public instance variables (fields) –Persistent values should be accessed through methods called getXxx and setXxx If class has method getTitle that returns a String, class is said to have a String property named title If class has method getTitle that returns a String, class is said to have a String property named title Boolean properties use isXxx instead of getXxx Boolean properties use isXxx instead of getXxx For more on beans, see For more on beans, see

34 Basic Bean Use in JSP Format: Format: Purpose: Allow instantiation of classes without explicit Java syntax Purpose: Allow instantiation of classes without explicit Java syntax Notes Notes –Simple interpretation: JSP action can be thought of as equivalent to the scriptlet –Simple interpretation: JSP action can be thought of as equivalent to the scriptlet –But useBean has two additional features Simplifies setting fields based on incoming request params Simplifies setting fields based on incoming request params Makes it easier to share beans Makes it easier to share beans

35 Accessing Bean Properties Format: Format: Purpose: Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java code Purpose: Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java code Notes Notes – is equivalent to the following JSP expression – is equivalent to the following JSP expression

36 Setting Bean Properties: Simple Case Format: Format: Purpose Purpose –Allow setting of bean properties (i.e., calls to setXxx) without explicit Java code Notes Notes – is equivalent to the following scriptlet – is equivalent to the following scriptlet

37 Example: StringBean public class StringBean { private String message = "No message specified"; private String message = "No message specified"; public String getMessage() { public String getMessage() { return(message); return(message); } public void setMessage(String message) { public void setMessage(String message) { this.message = message; this.message = message; }} Installed in normal servlet directory Installed in normal servlet directory

38 <OL> Initial value (getProperty): Initial value (getProperty): <jsp:getProperty name="stringBean" property="message" /> property="message" /> Initial value (JSP expression): Initial value (JSP expression): <jsp:setProperty name="stringBean" property="message" property="message" value="Best string bean: Fortex" /> value="Best string bean: Fortex" /> Value after setting property with setProperty: Value after setting property with setProperty: <jsp:getProperty name="stringBean" property="message" /> property="message" /> <LI> Value after setting property with scriptlet: Value after setting property with scriptlet: </OL> JSP Page That Uses StringBean

39 JSP Page That Uses StringBean

40 Associating Bean Properties with Request (Form) Parameters If property is a String, you can do If property is a String, you can do – ' /> Scripting expressions let you convert types, but you have to use Java syntax Scripting expressions let you convert types, but you have to use Java syntax The param attribute indicates that: The param attribute indicates that: –Value should come from specified request param –Simple automatic type conversion performed Using "*" for the property attribute indicates that: Using "*" for the property attribute indicates that: –Value should come from request parameter whose name matches property name –Simple type conversion should be performed

41 Setting Bean Properties Case 1: Explicit Conversion & Assignment... <jsp:setProperty name="entry" name="entry" property="itemID" property="itemID" value=' ' /> value=' ' />

42 Setting Bean Properties Case 1: Explicit Conversion & Assignment <% int numItemsOrdered = 1; try { numItemsOrdered = numItemsOrdered = Integer.parseInt(request.getParameter("numItems")); Integer.parseInt(request.getParameter("numItems")); } catch(NumberFormatException nfe) {} %> <jsp:setProperty name="entry" name="entry" property="numItems" property="numItems" value=" " /> value=" " />

43 Setting Bean Properties Case 1: Explicit Conversion & Assignment <% double discountCode = 1.0; try { String discountString = String discountString = request.getParameter("discountCode"); request.getParameter("discountCode"); discountCode = discountCode = Double.valueOf(discountString).doubleValue(); Double.valueOf(discountString).doubleValue(); } catch(NumberFormatException nfe) {} %> <jsp:setProperty name="entry" name="entry" property="discountCode" property="discountCode" value=" " /> value=" " />

44 Case 2: Associating Individual Properties with Input Parameters <jsp:useBean id="entry" class="cwp.SaleEntry" /> class="cwp.SaleEntry" /><jsp:setProperty name="entry" name="entry" property="itemID" property="itemID" param="itemID" /> param="itemID" /><jsp:setProperty name="entry" name="entry" property="numItems" property="numItems" param="numItems" /> param="numItems" /><jsp:setProperty name="entry" name="entry" property="discountCode" property="discountCode" param="discountCode" /> param="discountCode" />

45 Case 3: Associating All Properties with Input Parameters <jsp:useBean id="entry" class="cwp.SaleEntry" /> class="cwp.SaleEntry" />

46 Sharing Beans You can use scope attribute to specify where bean is stored You can use scope attribute to specify where bean is stored – – –Bean still also bound to local variable in _jspService Lets multiple servlets or JSP pages share data Lets multiple servlets or JSP pages share data Also permits conditional bean creation Also permits conditional bean creation –Create new object only if you can't find existing one

47 Values of the scope Attribute page page –Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean application application –Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()). ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined).

48 Values of the scope Attribute session session –Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from regular servlet code with getAttribute and setAttribute, as with normal session objects. request request –Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute