The Presentation Tier of the Java EE Architecture

Similar documents
COMP9321 Web Application Engineering

Advanced Internet Technology Lab # 5 Handling Client Requests

COMP9321 Web Application Engineering

Servlet Fudamentals. Celsina Bignoli

JSP Scripting Elements

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Session 8. Introduction to Servlets. Semester Project

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Servlet Basics. Agenda

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

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

Servlets and JSP (Java Server Pages)

COMP9321 Web Application Engineering

JavaServer Pages (JSP)

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Using JavaBeans with JSP

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

Unit 5 JSP (Java Server Pages)

Java Servlets. Preparing your System

Servlet and JSP Review

Introduction to JSP and Servlets Training 5-days

Session 9. Introduction to Servlets. Lecture Objectives

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

JAVA SERVLET. Server-side Programming PROGRAMMING

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

01KPS BF Progettazione di applicazioni web

Advanced Web Technology

JavaServer Pages. Juan Cruz Kevin Hessels Ian Moon

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

JavaServer Pages. What is JavaServer Pages?

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

AJP. CHAPTER 5: SERVLET -20 marks

Chapter 10 Servlets and Java Server Pages

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

JSP Scripting Elements

SERVLETS INTERVIEW QUESTIONS

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

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

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Module 4: SERVLET and JSP

Fast Track to Java EE

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

UNIT-V. Web Servers: Tomcat Server Installation:

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

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

JAVA. Web applications Servlets, JSP

CSC309: Introduction to Web Programming. Lecture 10

CE212 Web Application Programming Part 3

Questions and Answers

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Unit 4 Java Server Pages

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Web based Applications, Tomcat and Servlets - Lab 3 -

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

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:

Java Server Pages JSP

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Table of Contents. Introduction... xxi

JAVA SERVLET. Server-side Programming INTRODUCTION

Server Side Internet Programming

Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

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

The Structure and Components of

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Basic Principles of JSPs

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Servlets Basic Operations

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

CHAPTER 2: A FAST INTRODUCTION TO BASIC SERVLET PROGRAMMING

Using JavaBeans Components in JSP Documents

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Building Web Applications in WebLogic

HTTP and the Dynamic Web

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

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

Handling the Client Request: HTTP Request Headers

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

SNS COLLEGE OF ENGINEERING, Coimbatore

6- JSP pages. Juan M. Gimeno, Josep M. Ribó. January, 2008

JSP MOCK TEST JSP MOCK TEST IV

CSC309: Introduction to Web Programming. Lecture 11

Web Programming. Lecture 11. University of Toronto

ADVANCED JAVA TRAINING IN BANGALORE

Java E-Commerce Martin Cooke,

Handout 31 Web Design & Development

Principles and Techniques of DBMS 6 JSP & Servlet

ADVANCED JAVA COURSE CURRICULUM

Integrating Servlets and JavaServer Pages Lecture 13

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Université du Québec à Montréal

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

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

First Servlets. Chapter. Topics in This Chapter

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

Trabalhando com JavaServer Pages (JSP)

JSP. Common patterns

COMP201 Java Programming

Transcription:

The Presentation Tier of the Java EE Architecture Authors: Address: Version: 1.0 Simon Pickin Natividad Martínez Madrid Florina Almenárez Mendoza Departamento de Ingeniería Telemática Universidad Carlos III de Madrid Spain Acknowledgements: Marty Hall 1 Contents 1. Java Servlets 2. Java Server Pages (JSPs) 3. Integration of servlets and JSPs Bibliography: Core Servlets and JavaServer Pages, vol 1, 2nd edition. Marty Hall and Larry Brown. Prentice Hall 2003 Core Servlets and JavaServer Pages, vol 2, 2nd edition. Marty Hall, Larry Brown, Yaakov Chaikin. Prentice Hall 2007 Java for the Web with Servlets, JSP, and EJB. Budi Kurniawan. New Riders 2002. Part I, chapters 1-5, 8-11, 17 2 1

Web application architecture Servlets/JSPs Application conforming to a three-tier architecture (small-scale application with no business tier) Client Servlets JSP pages Web Container Presentation + Business logic 3 Presentation tier: Java Servlets 4 2

Contents: Java Servlets Generalities introduction advantages servlet life-cycle Servlet API interfaces, classes and methods HTTP servlets forwarding / including session tracking / session management 5 Introduction to Servlets (1/2) A servlet is a Java class used to extend the capabilities of the servers that host applications accessed via a client-server programming model normally used to extend the capabilities of web servers Comparable to a CGI (Common Gateway Interface) program but with a different architecture Managed by a servlet container or engine JVM + implementation of the servlet API 6 3

Introduction to Servlets (2/2) Client Web browser request Server Container (JRE) Servlet Servlet response Source: Web Component Development Wth Servlet and JSP Technologies Sun Microsystems (course SL-314-EE5) Interfaces and classes Packages javax.servlet y javax.servlet.http All servlets must implement the Servlet interface, which defines the life-cycle methods, or extend one of the classes: GenericServlet: handles generic services. HttpServlet: handles HTTP services extends GenericServlet 7 Advantages of using servlets (1/2) Efficiency one thread per request but single instance of each servlet time economy: no process creation delay on each request space economy: lower memory usage scalability servlet maintains its state between requests database connections, network connections, etc. requests handled via method execution Utilities for performing typical server tasks logging, error management, session management etc. standardised way of communicating with the server servlets can share data enables database connection pooling etc. 8 4

Advantages of using servlets (2/2) Advantages of Java large number of APIs: JDBC, threads, RMI, networks, etc. portability between platforms and servers security virtual machine, type-checking, memory management, exception handling, etc. security manager object-oriented large community of developers external code easily used 9 Servlet Life-Cycle Instantiation & initialisation (on first request): if no instance of servlet exists, the web container: loads the servlet class creates an instance initialises the instance by calling the servlet s init method Handling of subsequent requests container creates new thread that calls the service method of the instance the service method determines what type of request has arrived and calls the appropriate method. Destruction when the container decides to remove a servlet, it first calls its destroy method 10 5

Servlet Lifecycle Consequences (1/2) Single virtual machine: data sharing between servlets Persistence (in memory) of instances reduced memory consumption elimination of instantiation and initialisation time persistence (in memory) of state, data and resources persistent attributes of the servlet permanent database connections, etc persistence (in memory) of threads 11 Servlet Lifecycle Consequences (2/2) Concurrent requests need for synchronisation to manage concurrent access class or instance attributes, databases, etc. if servlet implements SingleThreadModel interface no concurrent access to instance attributes (may be concurrent access to class attributes) can lead to significantly-reduced performance deprecated since version 2.4 12 6

Contents: Java Servlets Generalities introduction advantages servlet tasks life-cycle API de Servlets interfaces, classes y methods HTTP servlets forwarding / including session tracking / session management 13 Servlet API Packages javax.servlet 6 interfaces Servlet ServletConfig ServletContext ServletRequest ServletResponse RequestDispatcher 3 classes GenericServlet ServletInputStream ServletOutputStream 2 exception classes ServletException UnavailableException 14 7

Servlet Interface Methods (1/2) void init(servletconfig config) called exactly once after servlet is instantiated servlet can be instantiated (depending on how registered) either when the first user accesses the servlet URL or when the web server is started without arguments: server-independent initialisation variable initialisation, connection to databases etc. with arguments: server-dependent initialisation info obtained from deployment descriptor web.xml (from servlet 2.3) and placed in ServletConfig object configuration of databases and password files, setting of serverefficiency parameters, etc. void service(servletrequest req, ServletResponse res) invoked by container to enable servlet to respond to request 15 Servlet Interface Methods (2/2) void destroy() container may decide to remove a previously-loaded servlet instance, e.g. system administrator decision timeout: idle for too long before doing so, calls the destroy method to cleanup close database connections stop threads write cookie lists or hit counts to disk if Web server crashes, destroy method not called! conclusion: maintain state in a proactive manner ( housekeeping at regular intervals) 16 8

ServletConfig Interface (1/3) Configuration object used by servlet container to pass information to the servlet during its initialisation config info obtained from the deployment descriptor web.xml for each servlet registered, a set of initial parameters (name-value) can be specified,e.g. <web-app> <servlet> <servlet-name>configexample</servlet-name> <servlet-class>configexampleservlet</servlet-class> <init-param> <param-name>adminemail</param-name> <param-value>admin@it.uc3m.es</param-value> </init-param> <init-param>... </init-param> </servlet>... </web-app> 17 ServletConfig Interface (2/3) Example: overwrite the init method in order to print the information contained in the ServletConfig object public void init(servletconfig config) throws ServletException { Enumeration parameters = config.getinitparameternames(); while (parameters.hasmoreelements()) { String parameter = (String) parameters.nextelement(); System.out.println("Parameter name : " + parameter); System.out.println("Parameter value : " + config.getinitparameter(parameter)); } } 18 9

ServletConfig Interface (3/3) N.B. if the init method (with parameters) of the Servlet interface (implemented in the GenericServlet class) is redefined, the ServletConfig object will not be saved and will not then be available after initialisation. Solution: either call Servlet.init (super.init if extending the GenericServlet or HttpServlet class) from inside the redefined init or explicitly save it, e.g. ServletConfig servlet_config; public void init(servletconfig config) throws ServletException { servlet_config = config; } The advantage of the former solution is that in this case the ServletConfig object will still be obtainable via the getservletconfig method whereas with the second solution it will not. 19 ServletContext Interface Defines a set of methods used by the servlet to communicate: with its container (to obtain MIME type of a file, a dispatcher etc.) with other servlets A context is defined per Web application per virtual machine Web application collection of servlets and contents installed in a specific subset (subdirectory) of the server namespace The information about the Web application of which a servlet forms a part is stored in the ServletConfig object 20 10

ServletContext Attributes The context is obtained from the configuration ServletContext sc = Servlet.getServletConfig().getServletContext(); Objects can be stored as attributes, identified by name sc.setattribute( myobject, anobject); If the name exists, the context is updated with the content of the new object Any servlet in the same context can recover the object that has been stored MyClass mc = (MyClass)sc.getAttribute( myobject ); The names of all the stored attributes can be obtained Enumeration att = sc.getattributenames(); 21 ServletRequest and ServletResponse Interfaces Objects created by the container and passed as arguments to the methods handling the request ServletRequest encapsulates request information includes parameters, attributes and an input stream methods: getparamaternames(), getparameter(), getattributenames(), getremoteaddr(), getremotehost(), getprotocol(), getcontenttype(), ServletResponse encapsulates response info methods: getwriter(), reset(), getbuffersize(), getlocale(), getoutputstream(), iscommitted(), 22 11

HTTP Servlets (javax.servlet.http) Inherits from javax.servlet.httpservlet The HttpServlet.service() method invokes the doxxx method according to the HTTP-method of incoming request void doget (HttpServletRequest req, HttpServletResponse res) void dopost(httpservletrequest req, HttpServletResponse res) void do...(httpservletrequest req, HttpServletResponse res) Overriding service() method not recommended Main work of the servlet usually done in doxxx method: example: to process GET requests redefine doget 23 The doget, dopost, doxxx Methods 99% of servlets override doget or dopost method Also: dodelete, doput, dooptions, dotrace No dohead method the service method simply calls doget but omits the body, returning only headers and status code In general, not necessary to define dooptions supported automatically by the service method (along with HEAD & TRACE) if doget method exists, the service method answers OPTIONS requests by returning an Allow header, indicating that GET, HEAD, OPTIONS y TRACE are supported 24 12

HttpServlet class Hello extends HttpServlet request GET service() doget() POST dopost() response Implemented by HttpServlet Implemented by the subclass 25 HTTP Servlet Tasks (1/2) 1. Read data sent by the user typically sent via a web page form may also originate in an applet or HTTP client app. 2. Retrieve user information in HTTP request headers browser capabilities cookies details of the client host etc. 3. Generate results directly calculating the response calling another (possibly remote) server (possibly accessed via RMI or CORBA) accessing a database, etc. 26 13

HTTP Servlet Tasks (2/2) 4. Format the results normally inside an HTML web page 5. Set the required HTTP response headers type of document returned (e.g. HTML) cookies cache parameters, etc 6. Return the document to the client in the form of a text document (e.g. HTML) binary format (e.g. GIF) compressed (e.g. gzip) 27 Basic HTTP Servlet Template import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { // Use "request" to read incoming HTTP headers (e.g. cookies) // and HTML form data (e.g. data user entered and submitted). // Use "response" to specify the HTTP response status code // and headers (e.g. the content type, cookies). public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } } // Use "out" to send content to browser. PrintWriter out = response.getwriter(); 28 14

Example 1: Text Generation (1/2) 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 { PrintWriter out = response.getwriter(); out.println("hello World"); } } 29 Example 1: Text Generation (2/2) 30 15

Example 2: HTML Generation (1/2) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOExceptio { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); String doctype = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" " + "\"http://www.w3.org/tr/1999/rec-html401-19991224/loose.dtd\" >\n"; out.println(doctype + "<html>\n" + "<head><title>hello WWW</title></head>\n" + "<body>\n" + "<h1>hello WWW</h1>\n" + "</body></html>"); } } 31 Example 2: HTML Generation (2/2) 32 16

HTTPServletRequest interface Reading HTML Form Data from Servlets http://host/path?user=marty+hall&origin=bwi&dest=lax form data / query data (GET) public String getparameter(string name) method of HttpServletRequest inherited from ServletRequest applies in case of data sent by GET or by POST (server knows which) name: name of parameter whose value is required (case sensitive) return value: url-decoded value of first occurrence of parameter name empty string if parameter exists but has no value null if parameter does not exist for parameters that potentially have several values: getparametervalues (returns an array of Strings) to obtain a complete list of parameters (debugging): getparameternames (returns an enumeration whose elements can be cast to Strings and used in getparameter calls) 33 Reading Form Data from a CGI Progam (for Comparison Purposes) http://host/path?user=marty+hall&origin=bwi&dest=lax CGI: Different methods for GET and POST form data / query data (GET) Parse the query string to extract names and values: 1. read data from QUERY_STRING environment variable (GET) or standard input (POST) 2. chop pairs at & (parameter separator) then separate parameter names (l.h.s of = ) from values (r.h.s. of = ) 3. URL-decode the parameter values Take into account that there may be parameters whose values are omitted for which multiple values are sent (separately) 34 17

Example 3: Reading three explicit parameters package coreservlets // source: Core Servlets, Marty Hall et al import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ThreeParams extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); String title = "Reading Three Request Parameters"; out.println(servletutilities.headwithtitle(title) + "<body bgcolor=\"#fdf5e6\">\n" + "<h1 align="center">" + title + "</h1>\n <ul>\n" + " <li><b>param1</b>: " + req.getparameter("param1") + "</li>\n" + " <li><b>param2</b>: " + req.getparameter("param2") + "</li>\n" + " <li><b>param3</b>: " + req.getparameter("param3") + "</li>\n" + "</ul>\n</body></html>"); } 35 } Example 3: ServletUtilities Class public class ServletUtilities { public static final String DOCtype = "<!DOCtype HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"" + " \"http://www.w3.org/tr/1999/rec-html401-19991224/loose.dtd\">"; public static String headwithtitle (String title) return(doctype + "\n" + "<html>\n" + "<head><title>" + title + "</title></head>\n"); } } 36 18

Example 3: HTML Form <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/loose.dtd"> <html> <head> <title>collecting Three Parameters</title> </head> <body bgcolor="#fdf5e6"> <h1 align="center">collecting Three Parameters</h1> <form action="/servlet/coreservlets.threeparams"> First Parameter: <input type="text" name="param1"><br /> Second Parameter: <input type="text" name="param2"><br /> Third Parameter: <input type="text" name="param3"><br /> <center><input type="submit" value="enviar consulta"></center> </form> </body> </html> 37 Example 3: HTML Form Appearance 38 19

Example 3: Servlet Response 39 Example 4: Reading All Parameters (1/3) package coreservlets // source: Core Servlets, Marty Hall et al import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowParameters extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); String title = "Reading All Request Parameters"; out.println(servletutilities.headwithtitle(title) + "<body bgcolor=\"#fdf5e6\">\n" + "<h1 align="center">" + title + "</h1>\n" + "<table border="1" align="center">\n" + "<tr bgcolor=\"#ffad00\">\n" + "<th>parameter name</th><th>parameter value(s)</th></tr>"); Enumeration paramnames = req.getparameternames(); 40 20

Example 4: Reading All Parameters (2/3) while (paramnames.hasmoreelements()) { String paramname = (String)paramnames.nextElement(); out.print("<tr><td>" + paramname + "</td>\n<td>"); String[] paramvalues = req.getparametervalues(paramname); if (paramvalues.length == 1) { String paramvalue = paramvalues[0]; if (paramvalue.length() == 0) out.println("<i>no value</i>"); else out.println(paramvalue); } else { out.println("<ul>"); for(int i=0; i<paramvalues.length; i++) out.println("<li>" + paramvalues[i] + "</li>"); out.println("</ul>"); } // if out.println("</td></tr>"); } // while } out.println("</table>\n</body></html>"); 41 Example 4: Reading All Parameters (3/3) } // Since servlet is for debugging, handle GET and POST identically. public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { } doget(req, res); 42 21

Example 4: HTML Form <form action="/servlet/coreservlets.showparameters" method="post"> Item Number: <input type="text" name="itemnum"><br /> Quantity: <input type="text" name="quantity"><br /> Price Each: <input type="text" name="price" value="$"><br /> <hr /> First name: <input type="text" name="firstname"><br /> Last name: <input type="text" name="lastname"><br /> Credit Card:<br /> <input type="radio" name="cardtype" value="visa">visa<br /> <input type="radio" name="cardtype" value="master Card">Master Card<br /> <input type="radio" name="cardtype" value="amex">american Express<br /> Credit Card Number: <input type="password" name="cardnum"><br /> Repeat Credit Card Number: <input type="password" name="cardnum"><br /> <center><input type="submit" value="submit Order"></center> </form> 43 Example 4: HTML Form Appearance 44 22

Example 4: Servlet Response 45 HTTPServletRequest interface Handling Request Headers (1/2) String getheader(string name) accepts header name as string (not case sensitive) returns header as string, or null if no header was found Cookie[] getcookies() returns contents of Cookie header as array of Cookie objects String getauthtype() y String getremoteuser() return the elements of the Authorization header int getcontentlength() returns value of ContentLength header or -1 if length unknown (length, in bytes, of request body for POST requests) String getcontenttype() returns the value of the Content-Type header 46 23

HTTPServletRequest interface Handling Request Headers (2/2) long getdateheader(string name) int getintheader(string name) returns the value of the specified header as a long or an int former returns value in milliseconds from Jan 1st 1970 Enumeration getheadernames() returns enumeration with names of all request headers received Enumeration getheaders(string name) returns enumeration with all values of all occurrences of the specified header (e.g. Accept-Language can appear several times) 47 HTTPServletRequest interface Handling the First Line of the Request String getmethod() returns the method of the request (GET, POST, etc.) String getrequesturi() returns path, i.e. part of the URI of the request between host:port and query string (recall: scheme://host:port/path?query_string) e.g. returns /a/b.html for HTTP request commencing as follows: GET /a/b.html?name=simon HTTP/1.1 Host: www.it.uc3m.es String getprotocol() returns the name and version of the protocol in the form: protocol/majorversion.minorversion example: HTTP/1.1 48 24

Example 5: Showing Request Headers (1/2) // source: Core Servlets, Marty Hall et al public class ShowHeadersServlet extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("request Method: " + request.getmethod() + "<br/>"); out.println("request URI: " + request.getrequesturi() + "<br/>"); out.println("protocol: " + request.getprotocol() + "<br/>"); out.println("<hr /><br />"); Enumeration enumeration = request.getheadernames(); while (enumeration.hasmoreelements()) { String header = (String) enumeration.nextelement(); out.println(header + ": " + request.getheader(header) + "<br/>"); } } 49 Example 5: Servlet Response 50 25

HTTPServletResponse Interface Setting Response HTTP Status Codes void setstatus(int sc) important: status code and headers can be set in any order (servlet orders them) but must always be set before using the PrintWriter. from version 2.2, some output buffering is permitted (headers and status codes can be modified until buffer full) accepts one of the constants defined as status codes void senderror(int status-code, String msg) void senderror(int status-code) sends a status code along with a short message that will be formatted inside HTML document and sent to client void sendredirect(string location) sends temporary redirect to client with new URL as parameter. from version 2.2, URL may be relative to servlet root (begins with / ) or current directory: conversion to full URL performed by web container. generates both status code and header 51 HTTPServletResponse Interface Setting Response Headers void setheader(string name, String value) sets header with identifier name to the value value void setdateheader(string name, long date) value in milliseconds since 1970 (System.currentTimeMillis) sets header name to value as GMT time string void setintheader(string name, int value) accepts value as integer sets header name to value as string From version 2.2 above methods re-set headers if called more than once. to add a header more than once use: addheader adddateheader addintheader 52 26

HTTPServletResponse Interface Setting Some Common Response Headers void setcontenttype(string type) generates the Content-Type header (MIME type of the contents). used by nearly all servlets void setcontentlength(int len) generates the Content-Length header void addcookie(cookie cookie) inserts a cookie in the Set-Cookie header void sendredirect(string location) mentioned previously 53 Example 6a: Authentication (1/3) public class LoginServlet extends HttpServlet { private void sendloginform(httpservletresponse response, boolean witherrormessage) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<head><title>login</title></head>"); out.println("<body>"); if (witherrormessage) out.println("login failed. Please try again.<br />"); out.println("<br />"); out.println("<br/>please enter your user name and password."); 54 27

Example 6a: Authentication (2/3) out.println("<br /><form action=\"\" method=\"post\">"); out.println("<br />User Name: <input type=\"text\" name=\"username\">"); out.println("<br />Password: <input type=\"password\" name=\"password\">"); out.println("<br /><input type=\"submit\" name=\"submit\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { sendloginform(response, false); } 55 Example 6a: Authentication (3/3) public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getparameter("username"); String password = request.getparameter("password"); if (username!=null && password!=null && username.equals("swc") && password.equals("it")) { response.sendredirect("http://domain/welcomepage"); } else { } sendloginform(response, true); } } response.senderror(response.sc_forbidden, "Login Failed"); 56 28

Example 6a: Servlet Response on Failure senderror 57 Example 6a: Servlet Response on Success String username = request.getparameter("username");... out.println("<p>your user name is: " + username + "</p>"); The request object is not the same one after redirection 58 29

Forwarding / Including Requests Use a RequestDispatcher Obtained by calling method getrequestdispatcher of ServletContext supplying URL relative to the server root as argument ServletRequest supplying URL relative to the HTTP request as argument Pass control to resource located at URL: forward arguments: request and response objects origin servlet cannot set output body origin servlet can set response headers but not commit them changes path to be relative to target not origin Include output generated by resource located at URL: include arguments: request and response objects target resource cannot modify response headers 59 Example 6b: Authentication (3/3) public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getparameter("username"); String password = request.getparameter("password"); if (username!=null && password!=null && username.equals("swc") && password.equals("it")) { RequestDispatcher rd = request.getrequestdispatcher("welcomepage"); response.sendredirect("http://domain/welcomepage"); rd.forward(request, response); } else { sendloginform(response, true); } } 60 30

Example 6b: Servlet Response on Success String username = request.getparameter("username");... out.println("<p>your user name is: " + username + "</p>"); The request object is the same one after forwarding 61 Cookies HTTP is a stateless protocol Cookies are small pieces of information sent from server to client in an HTTP response returned from client to server in subsequent HTTP requests A cookie is therefore a means for the server to store information on the client A cookie has a name and an identifier optionally, attributes such as path, comment, domain, maximum lifespan, version number 62 31

Use of Cookies State of an e-commerce session (session tracking) example: shopping cart Registering without login and password only for low-security sites site can remember user data Customising a site site can remember user interests Focusing advertising site can focus advertising in function of user activity profile 63 Problems with Cookies Not so much a security problem not executable or interpretable size and number (per site and total) is limited (4KB, 20, 300) Privacy problem servers can remember your previous actions cookies can be shared between servers e.g. both loading an image with associated cookie from third site; such images may even be received in an HTML e-mail! secret information (credit card no. etc.) should not be stored in a cookie but on the server cookie only stores user ID; as a user, how can we be sure? Many users deactivate cookies servlets can use cookies but are not dependent on them 64 32

Creating and Populating Cookies in Servlets Methods of the Cookie class Cookie(String name, String value) constructor receives the name and value of the cookie forbidden characters: [ ] ( ) =, /? @ : ; getxxx() y setxxx() where Xxx is the name of the attribute attributes: type String : Comment, Domain, Name, Path, Value type int : MaxAge, Version type boolean: Secure 65 Reading and Writing Cookies in Servlets To read cookies from the request object Cookie[] HttpServletRequest.getCookies() To write cookies to the response object void HttpServletResponse.addCookie(Cookie cookie) To reuse a cookie from the request: must still use addcookie (just using setvalue is not enough) must reset all attributes (values not transmitted in the request) See also method getcookievalue 66 33

Session Tracking Client at on-line shop adds item to their shopping cart: how does server know what s already in the cart Client at on-line shop proceeds to check-out how does server know which shopping cart is theirs? Implementing session tracking with cookies complicated: generate unique session ID, associate sessionid and session info in hash table, set cookie expiration time, Implementing session tracking with URL-rewriting must encode all URLs that refer to you own site all pages must be dynamically generated Implementing session tracking with hidden form fields tedious all pages must be the result of form submissions 67 Interfaz HttpSession: Session Object Creates a session between the HTTP client and the HTTP server that persists through different requests. Allows servlets to: see and manipulate session information such as session identifier, session creation time, last access time, link session objects, allowing user information to persist through different connections To obtain the session associated to a request use getsession() or getsession(boolean create) of HttpServletRequest if there is no session already associated to the request getsession()/ getsession(true) creates a new one getsession(false) returns null 68 34

Storing Information in Session Object Arbitrary objects can be stored inside a session uses hashtable-like mechanism store and retrieve with setattribute and getattribute To support distributed Web applications persistent sessions session data must implement java.io.serializable 69 Session Tracking: HttpSession (1/2) Associating information with a session void setattribute(string name, Object value) void setmaxinactiveinterval(int interval) void removeattribute(string name) Terminating completed or abandoned sessions automatically, after MaxInactiveInterval time has elapsed via the method void invalidate() 70 35

Session Tracking: HttpSession (2/2) Looking up information associated with a session Object getattribute(string name) Enumeration getattributenames() String getid() long getcreationtime() long getlastaccessedtime() ServletContext getservletcontext() int getmaxinactiveinterval() boolean isnew() 71 Session Tracking With Cookies Disabled Servlet session tracking mechanism uses cookies, if they are enabled, URL-rewriting, otherwise To ensure URL-rewriting works: encode URLs server uses cookies: no effect server uses URL-rewriting: session ID appended to URL http://host/path/file.html?jsession=1234 For any hypertext links back to same site in code use response.encodeurl For any use of sendredirect in code use response.encoderedirecturl 72 36

Executing Servlets Suppose this configuration of Tomcat Web server ( in web.xml file): <servlet> <servlet-name>firstservlet</servlet-name> <description>my first HTTP Servlet</description> <servlet-class>firstservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>firstservlet</servlet-name> <url-pattern>/servlets/myfirstservlet</url-pattern> </servlet-mapping> 1. Introduce URL of servlet in a browser, e.g. http://host/app/servlets/myfirstservlet 2. Call it from inside an HTML Web page link, form action or reloading specified in META tag, e.g. <a href= servlets/myfirstservlet >My first servlet</a> 3. Transfer control from another servlet, e.g. SendRedirect, RequestDispatcher 73 Presentation tier: JavaServer Pages 74 37

Contents: Java Server Pages Introduction Predefined variables JSP Instructions script directive action JavaBeans JSP Standard Tag Library (JSTL) Expression Language (EL) 75 Introducción Response HTML: servlets always generate all the page: in many cases only small part of HTML page is dynamic Solution: JavaServer Pages (JSP) technology enabling mixture of static HTML dynamic content generated by servlets Advantages of JSP: widely supported by web platforms and servers full access for dynamic part to servlet & Java technology (JavaBeans etc.) JSPs are compiled to servlets on first use or on deployment 76 38

JSP Processing hello.jsp <% Web server hello_jsp.java %> http://host/app/hello.jsp Container _jspservice jspdestroy hello_jsp jspinit «create» hello_jsp.class Source: Web Component Development Wth Servlet and JSP Technologies. Sun Microsystems (course SL-314-EE5) 77 Predefined Variables / Implicit Objects (1/2) request the HttpServletRequest object response the HttpServletResponse object session the HttpSession object associated with the request out the PrintWriter object used to send output to the client (this is a buffered PrintWriter called a JspWriter) page synonym of this (little used) 78 39

Predefined Variables / Implicit Objects (2/2) exception error pages application, the ServletContext object data can be stored in ServletContext using getattribute y setattribute recall: data stored in ServletContext shared by all servlets (of the same Web application) config the ServletConfig object for this page pagecontext object of JSP-specific class: PageContext, point of access to page attributes corresponds to the context of the servlet instance 79 JSP Instructions Three types of embedded instructions: script elements specify Java code that will become part of servlet directives control overall structure of servlet actions actions that take place when the page is requested control behaviour of JSP engine Comments: <%-- this is a comment --%> 80 40

Script Elements Expressions: <%= expression %> expressions to be evaluated; result included in output e.g. <%= new java.util.date() %> Scriptlets: <% code %> blocks of java code inserted into method _jspservice (called by service) e.g. <% try{... } catch(){... } %> Declarations: <%! code %> declarations inserted into servlet class body, outside of existing methods e.g. <%! int i=0; %> 81 Expressions: <%= expression %> Java expressions Output converted to a string Evaluated at run-time, when page requested access to information about request Final semi-colon ; not needed Examples <%= java.util.calendar.getinstance().gettime() %> <p>your session Id: <%= session.getid() %> request: http://host/confirmation.jsp?title=core+web response: Thanks for ordering <%= request.getparameter("title") %> 82 41

Example 1: Expressions // Source: Core Servlets, Marty Hall et al <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>jsp Expressions</title> <meta name="keywords" content="jsp,expressions,javaserver Pages,servlets" /> <meta name="description" content="a quick example of JSP expressions" /> <link rel="stylesheet" href="jsp-styles.css" type="text/css"/> </head> <body> <h1>jsp Expressions</h1> <ul> <li>current time: <%= new java.util.date() %></li> <li>server: <%= application.getserverinfo() %></li> <li>session ID: <%= session.getid() %></li> <li>the <code>testparam</code> form parameter: <%= request.getparameter("testparam") %></li> </ul> </body> </html> 83 Example 1: Server Response 84 42

Scriptlets: <% code %> Tasks that cannot be carried out using expressions setting response headers writing to the server log updating a database executing code that contains loops, conditionals, etc Examples: setting response headers <% response.setcontenttype( text/plain ); %> conditional code <% if (Math.random() < 0.5) { %> <p>have a <b>nice</b> day!</p> <% } else { %> <p>have a <b>lousy</b> day!</p> <% } %> 85 Example 2: Scriptlets // Source: Core Servlets, Marty Hall et al <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head><title>color Testing</title></head> <% String bgcolor = request.getparameter("bgcolor"); if ((bgcolor == null) (bgcolor.trim().equals(""))) { bgcolor = "WHITE"; } %> <body bgcolor="<%= bgcolor %>"> <h1 align="center">testing a Background of "<%= bgcolor %>" </h1> </body> </html> 86 43

Declarations: <%! declaration %> Definition of methods and fields inserted into servlet outside of existing methods Produces no output usually used in conjunction with expressions and scriptlets Examples <%! String getsystemtime() { return Calendar.getInstance().getTime.toString(); } %> <%! private int accesscount = 0; %> <h2>accesses to page since server reboot: <%= ++accesscount %></h2> 87 Example 3: Declarations // Source: Core Servlets, Marty Hall et al <!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> 88 44

Example 3: Some Observations Multiple client requests to same servlet: do not result in the creation of multiple servlet instances multiple threads call the service method of same instance though careful with use of SingleThreadModel Therefore: instance variables are shared by multiple requests accesscount does not need to be declared as static 89 Directives: <%@ directive attibutes %> Affect global structure of servlet generated from JSP Syntax: <%@ directive attribute="value" %> <%@ directive attribute1="value1... attributen="valuen" %> Three types of directives: page: allows servlet structure to be controlled through class imports, customising of servlet superclass, setting content type, etc. include: allows a file to be included in servlet class at time of translation from JSP to servlet taglib: allows custom markup tags to be defined, extending the functionality of JSP 90 45

Attributes of the page Directive import contenttype isthreadsafe session buffer autoflush extends info errorpage iserrorpage language 91 page Directive: import Attribute Specify the packages imported by the servlet By default, the generated servlet will import: java.lang.* javax.servlet.* javax.servlet.jsp.* javax.servlet.http.* and possibly others (server specific) Example: <%@ page import="java.util.*, java.io.*" %> 92 46

page Directive: contenttype Attribute Sets the Content-Type response header Example <%@ page contenttype="mime-type" %> <%@ page contenttype="mime-type; charset=character-set" %> <%@ page contenttype="text/html; charset=iso-8859-1" %> 93 The include Directive Use: <%@ include file= relative URL %> Adds content of specified file before translating to servlet included files may contain JSP constructs Code re-use Problem: not all servers detect when included file has changed to force re-compilation: change modification date of main file Unix touch command by explicitly modifying comment in main file such as: <%-- Navbar.jsp modified 03/01/03 --%> <%@ include file="navbar.jsp" %> See also jsp:include element 94 47

The taglib Directive Allows developers to define their own JSP tags Developer defines interpretation of: tag its attributes its body Custom tags can be grouped into tag libraries Components needed for using a custom tag library tag handler classes (java) or tag files (JSP) defines the behaviour associated to the tags tag library descriptor file (XML; file has.tld extension) info about the library and about each of its tags JSP files that use the tag library 95 Actions < jsp:action attributes > Tags interpreted at execution time jsp:include jsp:forward jsp:param jsp:usebean jsp:setproperty jsp:getproperty JavaBeans tags jsp:plugin jsp:params jsp:fallback HTML <object> tags 96 48

The jsp:include Action Adds content of specified file when request treated therefore, after translation to servlet Required attributes of include: page: a relative URL (JSP expressions can be used) flush: value is "true": any buffered content flushed to browser JSP 1.1: value "true" was mandatory Included files normally text or HTML files cannot contain JSP constructs may be result of resources that use JSP to generate output thus, URL may point to JSP or servlets 97 The jsp:forward Action Contents generated by the indicated JSP or servlet added to the response Control does not come back to original page stays with the forward page Attributes: page: a relative URL Interaction with output buffering (c.f. page directive, buffer attr.): forwarding leads to output buffer being cleared forwarding after output has been sent to browser: exception e.g. no buffer and some output sent e.g. buffer size exceeded and buffer defined as autoflush Example: <jsp:forward page="list.jsp" /> 98 49

The jsp:param Action For specifying parameters of passed-on request temporarily add new, or override existing, request param. retrieved with request.getparameter Attributes name: name of the parameter value: parameter value (JSP expressions can be used) Examples: <jsp:include page= header.jsp flush= true > <jsp:param name= title value= Welcome /> </jsp:include> <jsp:forward page= list.jsp > <jsp:param name= order value= A380 /> </jsp:forward> 99 JSP XML Syntax Script elements expressions <jsp:expression> Expression </jsp:expression> scriptlets <jsp:scriptlet> scriptlet code </jsp:scriptlet> declarations <jsp:declaration> declarations </jsp:declaration> Directives <jsp:directive:directivename attribute_list /> Template Data <jsp:text> text </jsp:text> 100 50

Example 4: Simple JSP <%@ page language= java contenttype= text/html;charset=iso-8859-1 %> <%@ page import= java.util.date %> <html> <head> <title>hola Mundo</title> </head> <body> <%! private int accesscount = 0; %> <p>hello, this is a JSP.</p> <p>the time on the server is <%= new Date() %>.</p> <p>this page has been accessed <%= ++accesscount %> times since server start-up.</p> </body> </html> 101 Example 4: Simple JSP Compiled to Servlet (Tomcat 5.x) import java.util.date; public class hello_jsp extends HttpJspBase { private int accesscount = 0; public void _jspservice(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } }... response.setcontenttype("text/html;charset=iso-8859-1"); pagecontext = _jspxfactory.getpagecontext(this, request, response, null, true, 8192, true); out = pagecontext.getout(); out.write("\r\n"); out.write("<html><head><title>hola Mundo</title></head>\r\n"); out.write(" <body>\r\n"); out.write(" <p>hello, this is a JSP.</p>\r\n"); out.write(" <p>the time on the server is " + new Date() + ".</p>\r\n"); out.write(" <p>this page has been accessed " + ++accesscount ); out.write(" times since server start-up.</p>\r\n"); out.write("</body></html>\r\n");... 102 51

Ejemplo 4: Server Response Hello, this is a JSP The time on the server is Tue Oct 16 21:58:11 CEST 2007 This page has been accessed 3 times since server start-up 103 Java Beans All data fields private: called properties Reading/writing bean data getxxx method (accessor) setxxx method (mutator) Events beans can send notifications of property changes Introspection self-knowledge Serializability Customisation property editors 104 52

Why Use JavaBeans? Reusability and modularity seperate java classes easier to write, compile, test, debug and reuse instead of large quantities of code embedded in JSP pages Clear separation between content and presentation java objects manipulated using XML-compatible syntax Easier to share objects between JSPs and servlets Can be used to simplify the process of reading request parameters 105 The jsp:usebean Action <jsp:usebean id="name" class="package.class" /> Meaning: instantiate an object of the class indicated in the class attribute bind it to a variable whose name is indicated in the id attribute Alternative use the beanname attribute instead of the class attribute the beanname attribute can refer to a file containing a serialized Bean Accessing properties: <jsp:getproperty name="book1" property="title" /> is equivalent to: <%= book1.gettitle() %> Assigning to properties: <jsp:setproperty name="book1" property="title" value="bible" /> is equivalent to: <%= book1.settitle("bible") %> 106 53

The jsp:setproperty Action (1/2) Usually, attribute values must be strings JSP expressions can be used in the attributes: name, value Example: setting a property to the value of a request parameter: <jsp:setproperty name="entry" property="itemid" value='<%= request.getparameter("itemid") %>' /> Problem: what happens if the property is not of type String? explicit type conversion (inside try-catch), but see next slide 107 The jsp:setproperty Action (2/2) Associating value of property to that of request parameter parameter and property have different names: <jsp:setproperty name="customer" property="email" param="new_email" /> is equivalent to customer.setemail(request.getparameter("new_email") parameter and property have identical names: <jsp:setproperty name="customer" property="email" /> is equivalent to customer.setemail(request.getparameter("email") Associating values of all properties with identically-named request parameters: <jsp:setproperty name="customer" property="*" /> In these cases, type conversion is automatic 108 54

Example 5: Simple Bean // Source: Core Servlets, Marty Hall et al package coreservlets; public class StringBean { private String message = "No message specified"; public String getmessage() { return(message); } public void setmessage(string message) { this.message = message; } } 109 Example 5: JSP Including Simple Bean <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head><title>using JavaBeans with JSP</title> <link rel="stylesheet" href="jsp-styles.css" type="text/css" /> </head> <body> <table border="5" align="center"> <tr><th class="title">using JavaBeans with JSP</th></tr></table> <jsp:usebean id="messagebean" class="coreservlets.messagebean" /> <ol> <li>initial value (print with getproperty): <i><jsp:getproperty name="messagebean" property="message" /></i></li> <li>initial value (print with JSP expression): <i><%= messagebean.getmessage() %></i></li> <li><jsp:setproperty name="messagebean" property="message" value="best message bean: Fortex" /> Value after setting property with setproperty (print with getproperty): <i><jsp:getproperty name="messagebean" property="message" /></i></li> <li><% messagebean.setmessage("my favorite: Kentucky Wonder"); %> Value after setting property with scriptlet (print with JSP expression): <i><%= messagebean.getmessage() %></i></li> </ol> </body> 110 </html> 55

Example 5: Server Response 111 Bean Scope In the JSP context beans created with jsp:usebean bound to a local variable four possibilities regarding their storage location scope attribute 112 56

Bean Scope Attribute scope of action jsp:usebean takes one of values: page (default value). placed in pagecontext object for duration of current request accessible through predefined variable pagecontext request stored in the ServletRequest object accessible through predefined variable request session stored in the HttpSession accessible through predefined variable session application stored in the ServletContext object accessible through predefined variable application 113 Bean Scope 114 57

Conditional Creation of Beans The jsp:usebean action instantiates new bean if no bean with same id & scope found otherwise, existing bean associated to variable referenced by id If, instead of: <jsp:usebean /> we write: <jsp:usebean > sentences </jsp:usebean> then sentences are executed only when new bean created convenient for setting initial bean properties for shared beans all pages that share the bean have the initialisation code 115 Expression Language (EL) First introduced with JSTL (Java Standard Tag Library) later extended for use anywhere (outside JSTL tags): JSP 2.0 EL Facilitates writing scriptlets in JSP pages Syntax: ${expression} an EL expression may be escaped (& not evaluated) with \ EL expressions may be used as values of attributes in actions, e.g. <jsp:include page="${location}"> inside the text of a template, such as HTML, e.g. <h1>welcome ${name}</h1> Example set attribute (in this case in a servlet) request.setattribute("endmessage","that's all Folks!"); use attribute in JSP (four scopes searched for attribute): <h2>${endmessage}</h2> 116 58

JSP Standard Tag Library (JSTL) JSTL is a standardised set of tag libraries encapsulates JSP functionality common to many applications Syntax <prefix:tagname (attributename= attributevalue )* /> <prefix:tagname>body</prefix:tagname> Functional areas: Core Area URI http://java.sun.com/jsp/jstl/core Prefix c XML processing http://java.sun.com/jsp/jstl/xml x Formatting / internationalisation http://java.sun.com/jsp/jstl/fmt fmt Relational database access http://java.sun.com/jsp/jstl/sql sql Functions http://java.sun.com/jsp/jstl/functions fn 117 Some of the JSTL Core Tags (1/2) set creates an EL variable updates value of existing EL variable or of JavaBean property <c:set [var="varname ] [value="value"] [scope="{page request session application}"] [target="variable.bean"][property="bean.property"] /> remove deletes an EL variable <c:remove var="varname" [scope="{page request session application}"] /> url provides an encoded (relative) URL, if cookies are disabled (for session management purposes) <c:url [value="value"] [var="varname"] [context="some"] [scope="{page request session application}"] /> 118 59

Some of the JSTL Core Tags (2/2) if (see also tags choose / when / otherwise) <c:if test="expression" [var="varname ] [scope="{page request session application}"] > body if expression is true </c:if> foreach out iteration over the content of the tag <c:foreach items="collection" [var="varname"] [ ]> body content </c:foreach> evaluates an expression and writes results in current JSPWriter <c:out value="value" [default="defaultvalue"] [escapexml="{true false}"] /> 119 Example 6: JSTL and EL <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:if test="${not empty errormsgs}" > <p>please correct the following errors: <ul> <c:foreach var="message" items="${errormsgs}"> <li>${message}</li> </c:foreach> </ul> </p> <p>accessing messagebean properties: ${messagebean.message}</p> </c:if> previously stored in one of the objects: pagecontext, request, session, or application 60

Presentation tier: Integration of Servlets and JSPs 121 Contents: Integration of Servlets and JSPs Integration de servlets and JSPs Handling a single request Forwarding in servlets and JSPs The MVC design pattern 122 61

Integration of Servlets and JSP Advantage of JSP over servlets easier to generate the static part of the HTML Problem JSP document provides a single overall presentation Solution combine servlets and JSP servlet: handles initial request partially processes data configures the beans passes results to one of a number of different JSP pages depending on circumstance 123 Handling a Single Request Servlet-only solution suitable when output is a binary type or there is no output format/layout of the page is highly variable JSP-only solution suitable when output is mostly character data format/layout mostly fixed Servlet & JSP combination solution suitable when single request has several possible responses, each with different layout business logic and Web presentation not developed by same people application performs complicated data processing but has relatively fixed layout 124 62

Forwarding in Servlets and JSPs From a JSP (unusual) LoginServlet <jsp:forward page='login.jsp'> <jsp:param name='login' value='pepe' /> </jsp:forward> From a Servlet RequestDispatcher rd = getservletcontext().getrequestdispatcher( "login.jsp?login=pepe"); rd.forward(request, response); LoginServlet?login=pepe 125 Example 1: Request Forwarding public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException IOException { String operation = request.getparameter("operation"); if (operation == null) { operation = "unknown"; } String address; if (operation.equals("order")) { address = "/WEB-INF/Order.jsp"; else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp"; else address = "/WEB-INF/UnknownOperation.jsp"; } } RequestDispatcher dispatcher = request.getrequestdispatcher(address); dispatcher.forward(request, response); 126 63

Model-View-Controller (MVC) Pattern Design Pattern (such as MVC) repeatable solution to commonly-occurring software problem MVC pattern well suited when single request can result in responses with different format several pages have substantial common processing Model the data to be manipulated and displayed View the actual display Controller handles the request decides what logic to invoke decides which view applies 127 MVC Pattern: More Detail Source: Java BluePrints, Model-View-Controller. Available at: http://java.sun.com/blueprints/patterns/mvc-detailed.html 128 64