JSP Scripting Elements

Similar documents
JSP Scripting Elements

Servlet and JSP Review

INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Topics in This Chapter

CSC309: Introduction to Web Programming. Lecture 10

JavaServer Pages. Juan Cruz Kevin Hessels Ian Moon

Integrating Servlets and JavaServer Pages Lecture 13

1.264 Lecture 15. Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages

COMP9321 Web Application Engineering

CSC309: Introduction to Web Programming. Lecture 11

COMP9321 Web Application Engineering

Web Programming. Lecture 11. University of Toronto

Unit 5 JSP (Java Server Pages)

COMP9321 Web Application Engineering

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

directive attribute1= value1 attribute2= value2... attributen= valuen %>

Advantage of JSP over Servlet

Experiment No: Group B_2

COMP201 Java Programming

Integrating Servlets and JSP: The MVC Architecture

UNIT -5. Java Server Page

JavaServer Pages (JSP)

Java Server Page (JSP)

core programming JavaServer Pages JSP Marty Hall, Larry Brown

CE212 Web Application Programming Part 3

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, JSPs 1

Unit 4 Java Server Pages

Using JavaBeans with JSP

Java Server Pages JSP

UNIT 6:CH:14 INTEGRATING SERVLETS AND JSPTHE MVC ARCHITECTURE

01KPS BF Progettazione di applicazioni web

Servlet Basics. Agenda

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Introduction to Java Server Pages. Enabling Technologies - Plug-ins Scripted Pages

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

One application has servlet context(s).

Java E-Commerce Martin Cooke,

Ch04 JavaServer Pages (JSP)

Review. For live Ajax & GWT training, see training courses at Taught by the author of Core Servlets and JSP,

JavaServer Pages. What is JavaServer Pages?

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

1. Introduction. 2. Life Cycle Why JSP is preferred over Servlets? 2.1. Translation. Java Server Pages (JSP) THETOPPERSWAY.

Java Server Pages. Copyright , Xiaoping Jia. 7-01/54

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Jakarta Struts: Declarative Exception Handling

The JSP page Directive: Structuring Generated Servlets

Principles and Techniques of DBMS 6 JSP & Servlet

CS433 Technology Overview

Basic Principles of JSPs

Enterprise Computing with Java MCA-305 UNIT II. Learning Objectives. JSP Basics. 9/17/2013MCA-305, Enterprise Computing in Java

JAVA SERVLET. Server-side Programming INTRODUCTION

SSC - Web development Model-View-Controller for Java Servlet

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Fast Track to Java EE 5 with Servlets, JSP & JDBC

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

JSP MOCK TEST JSP MOCK TEST III

Trabalhando com JavaServer Pages (JSP)

SNS COLLEGE OF ENGINEERING, Coimbatore

More JSP. Advanced Topics in Java. Khalid Azim Mughal Version date: ATIJ More JSP 1/42

About the Authors. Who Should Read This Book. How This Book Is Organized

********************************************************************

CISH-6510 Web Application Design and Development. JSP and Beans. Overview

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Module 4: SERVLET and JSP

PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II

ServletConfig Interface

Three hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE. Date: Friday 21 st May Time:

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Using JavaBeans Components in JSP Documents

Advanced Internet Technology Lab # 4 Servlets

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Introduction. This course Software Architecture with Java will discuss the following topics:

Component Based Software Engineering

SERVLET AND JSP FILTERS

JSP: Servlets Turned Inside Out

Trabalhando com JavaServer Pages (JSP)

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

JSP - ACTIONS. There is only one syntax for the Action element, as it conforms to the XML standard:

Advanced Java Programming

Java Server Pages. JSP Part II

A JavaBean is a class file that stores Java code for a JSP

Exercise. (1) Which of the following can not be used as the scope when using a JavaBean with JSP? a. application b. session c. request d.

Integrating Servlets and JSP: The Model View Controller (MVC) Architecture

The Presentation Tier of the Java EE Architecture

Unit 4. CRM - Web Marketing 4-1

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

20/08/56. Java Technology, Faculty of Computer Engineering, KMITL 1

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Model View Controller (MVC)

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM Advanced Internet Technology Lab.

AN ISO 9001:2008 CERTIFIED COMPANY ADVANCED. Java TRAINING.

Introduction to JSP and Servlets Training 5-days

Java Server Pages(JSP) Unit VI

Objec&ves. Servlets Review JSPs Web Applica&on Organiza&on Version Control. May 3, 2016 Sprenkle - CS335 1

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

JSP. Basic Elements. For a Tutorial, see:

Stateless -Session Bean

Servlets. An extension of a web server runs inside a servlet container

Transcription:

JSP Scripting Elements Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet and JSP Training Courses: courses.coreservlets.com 1 Slides Marty Hall, http://, book Sun Microsystems Press Agenda Basic syntax Types of JSP scripting elements Expressions Predefined variables Scriptlets Declarations 2 Scripting Elements

Uses of JSP Constructs Simple Application Complex Application Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Custom tags Servlet/JSP combo (MVC), with beans and possibly custom tags 3 Scripting Elements Design Strategy: Limit Java Code in JSP Pages You have two options Put 25 lines of Java code directly in the JSP page Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it Why is the second option much better? Development. You write the separate class in a Java environment (editor or IDE), not an HTML environment Debugging. If you have syntax errors, you see them immediately at compile time. Simple print statements can be seen. Testing. You can write a test routine with a loop that does 10,000 tests and reapply it after each change. Reuse. You can use the same class from multiple pages. 4 Scripting Elements

Basic Syntax HTML Text <H1>Blah</H1> Passed through to client. Really turned into servlet code that looks like out.print("<h1>blah</h1>"); HTML Comments <!-- Comment --> Same as other HTML: passed through to client JSP Comments <%-- Comment --%> Not sent to client To get <% in output, use <\% 5 Scripting Elements Types of Scripting Elements Expressions Format: <%= expression %> Evaluated and inserted into the servlet s output. I.e., results in something like out.print(expression) Scriptlets Format: <% code %> Inserted verbatim into the servlet s _jspservice method (called by service) Declarations Format: <%! code %> Inserted verbatim into the body of the servlet class, outside of any existing methods 6 Scripting Elements

JSP Expressions Format <%= Java Expression %> 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 Current time: <%= new java.util.date() %> Your hostname: <%= request.getremotehost() %> XML-compatible syntax <jsp:expression>java Expression</jsp:expression> XML version not supported by Tomcat 3. Until JSP 1.2, servers are not required to support it. Even then, you cannot mix versions within a single page. 7 Scripting Elements JSP/Servlet Correspondence Original JSP <H1>A Random Number</H1> <%= Math.random() %> Possible resulting servlet code public void _jspservice(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); HttpSession session = request.getsession(true); JspWriter out = response.getwriter(); out.println("<h1>a Random Number</H1>"); out.println(math.random());... 8 Scripting Elements

Example Using JSP Expressions <BODY> <H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.util.date() %> <LI>Your hostname: <%= request.getremotehost() %> <LI>Your session ID: <%= session.getid() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.getparameter("testparam") %> </UL> </BODY> 9 Scripting Elements Predefined Variables request The HttpServletRequest (1st argument to service/doget) response The HttpServletResponse (2nd arg to service/doget) out The Writer (a buffered version of type JspWriter) used to send output to the client session The HttpSession associated with the request (unless disabled with the session attribute of the page directive) application The ServletContext (for sharing data) as obtained via getservletcontext(). 10 Scripting Elements

JSP Scriptlets Format <% Java Code %> Result Code is inserted verbatim into servlet's _jspservice Example <% String querydata = request.getquerystring(); out.println("attached GET data: " + querydata); %> <% response.setcontenttype("text/plain"); %> XML-compatible syntax <jsp:scriptlet>java Code</jsp:scriptlet> 11 Scripting Elements JSP/Servlet Correspondence Original JSP <%= foo() %> <% bar(); %> Possible resulting servlet code public void _jspservice(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); HttpSession session = request.getsession(true); JspWriter out = response.getwriter(); out.println(foo()); bar();... 12 Scripting Elements

Example Using JSP Scriptlets <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Color Testing</TITLE> </HEAD> <% String bgcolor = request.getparameter("bgcolor"); boolean hasexplicitcolor; if (bgcolor!= null) { hasexplicitcolor = true; else { hasexplicitcolor = false; bgcolor = "WHITE"; %> 13 Scripting Elements Example Using JSP Scriptlets (Continued) <BODY BGCOLOR="<%= bgcolor %>"> <H2 ALIGN="CENTER">Color Testing</H2> <% if (hasexplicitcolor) { else { %> </BODY> </HTML> 14 Scripting Elements

JSP Scriptlets: Results 15 Scripting Elements Using Scriptlets to Make Parts of the JSP File Conditional Point Scriplets are inserted into servlet exactly as written Need not be complete Java expressions Complete expressions are usually clearer and easier to maintain, however Example <% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% else { %> Have a <B>lousy</B> day! <% %> Representative result if (Math.random() < 0.5) { out.println("have a <B>nice</B> day!"); else { out.println("have a <B>lousy</B> day!"); 16 Scripting Elements

JSP Declarations Format <%! Java Code %> Result Code is inserted verbatim into servlet's class definition, outside of any existing methods Examples <%! private int somefield = 5; %> <%! private void somemethod(...) {... %> Design consideration Fields are clearly useful. For methods, it is usually better to define the method in a separate Java class. XML-compatible syntax <jsp:declaration>java Code</jsp:declaration> 17 Scripting Elements JSP/Servlet Correspondence Original JSP <H1>Some Heading</H1> <%! private String randomheading() { return("<h2>" + Math.random() + "</H2>"); %> <%= randomheading() %> (Alternative: make randomheading a static method in a separate Java class) 18 Scripting Elements

JSP/Servlet Correspondence Possible resulting servlet code public class xxxx implements HttpJspPage { private String randomheading() { return("<h2>" + Math.random() + "</H2>"); public void _jspservice(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); HttpSession session = request.getsession(true); JspWriter out = response.getwriter(); out.println("<h1>some Heading</H1>"); out.println(randomheading());...... 19 Scripting Elements Example Using JSP Declarations <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD><TITLE>JSP Declarations</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>JSP Declarations</H1> <%! private int accesscount = 0; %> <H2>Accesses to page since server reboot: <%= ++accesscount %></H2> </BODY> </HTML> 20 Scripting Elements

JSP Declarations: Result After 15 total visits by an arbitrary number of different clients 21 Scripting Elements JSP Declarations: the jspinit and jspdestroy Methods JSP pages, like regular servlets, sometimes want to use init and destroy Problem: the servlet that gets built from the JSP page might already use init and destroy Overriding them would cause problems. Thus, it is illegal to use JSP declarations to declare init or destroy. Solution: use jspinit and jspdestroy. The auto-generated servlet is guaranteed to call these methods from init and destroy, but the standard versions of jspinit and jspdestroy are empty (placeholders for you to override). 22 Scripting Elements

JSP Declarations and Predefined Variables Problem The predefined variables (request, response, out, session, etc.) are local to the _jspservice method. Thus, they are not available to methods defined by JSP declarations or to methods in helper classes. What can you do about this? Solution: pass them as arguments. E.g. <%! private void somemethod(httpsession s) { dosomethingwith(s); %> <% somemethod(session); %> Note that the println method of JspWriter throws IOException Use throws IOException for methods that use println 23 Scripting Elements Using JSP Expressions as Attribute Values Static Value <jsp:setproperty name="author" property="firstname" value="marty" /> Dynamic Value <jsp:setproperty name="user" property="id" value= <%= "UserID" + Math.random() %> /> 24 Scripting Elements

Attributes That Permit JSP Expressions The name and value properties of jsp:setproperty See upcoming section on beans The page attribute of jsp:include See upcoming section on including files and applets The page attribute of jsp:forward See upcoming section on integrating servlets and JSP The value attribute of jsp:param See upcoming section on including files and applets 25 Scripting Elements Summary JSP Expressions Format: <%= expression %> Wrapped in out.print and inserted into _jspservice JSP Scriptlets Format: <% code %> Inserted verbatim into the servlet s _jspservice method JSP Declarations Format: <%! code %> Inserted verbatim into the body of the servlet class Predefined variables request, response, out, session, application Limit the Java code that is directly in page Use helper classes, beans, custom tags, servlet/jsp combo 26 Scripting Elements