Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
The Presentation Tier of the Java EE Architecture Communication Software 2010-2011 Authors: Simon Pickin Natividad Martínez Madrid Florina Almenárez Mendoza Address: Departamento de Ingeniería Telemática Universidad Carlos III de Madrid Spain Version: 1.1 Acknowledgements: Marty Hall 1 © The Authors Contents 1. Java Servlets – – – – – introduction the servlet API; interfaces classes and methods HTTP servlets forwarding and including session tracking and session management 2. JavaServer Pages (JSPs) – – – – – introduction predefined variables scripts, directives and actions JSPs and java beans JSP 2.0, JSTL and EL 3. Integration of Servlets and JSPs Communication Software 2010-2011 – – – joint use of servlets and JSPs forwarding in servlets and JSPs the MVC design pattern © The Authors 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 Communication Software 2010-2011 Presentation + Business logic 3 © The Authors 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 Communication Software 2010-2011 4 © The Authors 2 Introduction to Servlets (2/2) request Client Server Container (JRE) Web browser Servlet 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: Communication Software 2010-2011 – GenericServlet: handles generic services. – HttpServlet: handles HTTP services – extends GenericServlet 5 © The Authors 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. • Communication Communication Software 2010-2011 © The Authors – standardised way of communicating with the server – servlets can share data • enables database connection pooling etc. 6 3 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 Communication Software 2010-2011 7 © The Authors 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 Communication Software 2010-2011 – when the container decides to remove a servlet, it first calls its destroy method 8 © The Authors 4 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 Communication Software 2010-2011 9 © The Authors 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 Communication Software 2010-2011 10 © The Authors 5 Contents: Java Servlets • Generalities – – – – introduction advantages servlet tasks life-cycle • API de Servlets Communication Software 2010-2011 – – – – interfaces, classes y methods HTTP servlets forwarding / including session tracking / session management 11 © The Authors Servlet API • Packages – javax.servlet • 6 interfaces – Servlet – ServletConfig • 3 classes – GenericServlet – ServletInputStream – ServletOutputStream • 2 exception classes – ServletContext – ServletException – ServletRequest – UnavailableException – ServletResponse – RequestDispatcher Communication Software 2010-2011 12 © The Authors 6 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) Communication Software 2010-2011 – invoked by container to enable servlet to respond to request 13 © The Authors 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) Communication Software 2010-2011 14 © The Authors 7 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>[email protected]</param-value> </init-param> <init-param> . . . </init-param> </servlet> . . . </web-app> Communication Software 2010-2011 15 © The Authors 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 System.out.println("Parameter name : " + parameter); value : " + config.getInitParameter(parameter)); } } Communication Software 2010-2011 16 © The Authors 8 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; } Communication Software 2010-2011 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. 17 © The Authors 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 Communication Software 2010-2011 18 © The Authors 9 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(); Communication Software 2010-2011 19 © The Authors 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(), … Communication Software 2010-2011 20 © The Authors 10 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 Communication Software 2010-2011 21 © The Authors 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 Communication Software 2010-2011 22 © The Authors 11 HttpServlet class Hello extends HttpServlet request doGet() GET service() doPost() POST response Implemented by HttpServlet Implemented by the subclass Communication Software 2010-2011 23 © The Authors 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) Communication Software 2010-2011 • accessing a database, etc. 24 © The Authors 12 HTTP Servlet Tasks (2/2) 4. Format the results • 5. normally inside an HTML web page 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)… Communication Software 2010-2011 25 © The Authors 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(); Communication Software 2010-2011 } } 26 © The Authors 13 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"); } } Communication Software 2010-2011 27 © The Authors Example 1: Text Generation (2/2) Communication Software 2010-2011 28 © The Authors 14 Example 2: HTML Generation (1/2) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; Communication Software 2010-2011 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>"); } } 29 © The Authors Example 2: HTML Generation (2/2) Communication Software 2010-2011 30 © The Authors 15 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 • to obtain a complete list of parameters (debugging): – getParameterNames Communication Software 2010-2011 (returns an array of Strings) (returns an enumeration whose elements can be cast to Strings and used in 31 getParameter calls) © The Authors Reading Form Data from a CGI Progam (for Comparison Purposes) http://host/path?user=Marty+Hall&origin=bwi&dest=lax form data / query data (GET) CGI: • Different methods for GET and POST • 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 • Communication Software 2010-2011 Take into account that there may be parameters – – whose values are omitted for which multiple values are sent (separately) 32 © The Authors 16 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.*; Communication Software 2010-2011 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>"); } 33 } © The Authors 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"); } } Communication Software 2010-2011 34 © The Authors 17 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> Communication Software 2010-2011 35 © The Authors Example 3: HTML Form Appearance Communication Software 2010-2011 36 © The Authors 18 Example 3: Servlet Response Communication Software 2010-2011 37 © The Authors Example 4: Reading All Parameters (1/3) package coreservlets import import import import // source: “Core Servlets…”, Marty Hall et al java.io.*; javax.servlet.*; javax.servlet.http.*; 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>"); Communication Software 2010-2011 Enumeration paramnames = req.getParameterNames(); 38 © The Authors 19 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 Communication Software 2010-2011 out.println("</table>\n</body></html>"); 39 } © The Authors 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); } } Communication Software 2010-2011 40 © The Authors 20 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> Communication Software 2010-2011 </form> 41 © The Authors Example 4: HTML Form Appearance Communication Software 2010-2011 42 © The Authors 21 Example 4: Servlet Response Communication Software 2010-2011 43 © The Authors 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() Communication Software 2010-2011 – returns the value of the Content-Type header 44 © The Authors 22 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) Communication Software 2010-2011 45 © The Authors 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” Communication Software 2010-2011 46 © The Authors 23 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/>"); Communication Software 2010-2011 } } 47 © The Authors Example 5: Servlet Response Communication Software 2010-2011 48 © The Authors 24 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. Communication Software 2010-2011 – generates both status code and header 49 © The Authors 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 • Communication Software 2010-2011 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 50 © The Authors 25 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 Communication Software 2010-2011 51 © The Authors 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."); Communication Software 2010-2011 52 © The Authors 26 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); } Communication Software 2010-2011 53 © The Authors 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); } } Communication Software 2010-2011 } response.sendError(response.SC_FORBIDDEN, "Login Failed"); 54 © The Authors 27 Example 6a: Servlet Response on Failure sendError Communication Software 2010-2011 55 © The Authors Example 6a: Servlet Response on Success String userName = request.getParameter("userName"); . . . out.println("<p>Your user name is: " + userName + "</p>"); Communication Software 2010-2011 • The request object is not the same one after redirection 56 © The Authors 28 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 Communication Software 2010-2011 – target resource cannot modify response headers 57 © The Authors 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); } } Communication Software 2010-2011 58 © The Authors 29 Example 6b: Servlet Response on Success Communication Software 2010-2011 String userName = request.getParameter("userName"); . . . out.println("<p>Your user name is: " + userName + "</p>"); • The request object is the same one after forwarding 59 © The Authors 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 Communication Software 2010-2011 – a name and an identifier – optionally, attributes such as path, comment, domain, maximum lifespan, version number 60 © The Authors 30 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 Communication Software 2010-2011 61 © The Authors 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 Communication Software 2010-2011 – servlets can use cookies but are not dependent on them 62 © The Authors 31 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 Communication Software 2010-2011 63 © The Authors 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 Communication Software 2010-2011 64 © The Authors 32 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 Communication Software 2010-2011 – tedious – all pages must be the result of form submissions 65 © The Authors 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 Communication Software 2010-2011 66 © The Authors 33 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 Communication Software 2010-2011 67 © The Authors 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() Communication Software 2010-2011 68 © The Authors 34 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() Communication Software 2010-2011 69 © The Authors 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 Communication Software 2010-2011 – use response.encodeRedirectURL 70 © The Authors 35 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> Communication Software 2010-2011 3. Transfer control from another servlet, e.g. – SendRedirect, RequestDispatcher 71 © The Authors Contents 1. Java Servlets – – – – – introduction the servlet API; interfaces classes and methods HTTP servlets forwarding and including session tracking and session management 2. JavaServer Pages (JSPs) – – – – – introduction predefined variables scripts, directives and actions JSPs and java beans JSP 2.0, JSTL and EL 3. Integration of Servlets and JSPs Communication Software 2010-2011 – – – joint use of servlets and JSPs forwarding in servlets and JSPs the MVC design pattern © The Authors 36 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 Communication Software 2010-2011 73 © The Authors JSP Processing Web server hello.jsp hello_jsp.java <% %> Container jspDestroy http://host/app/hello.jsp _jspService hello_jsp jspInit Communication Software 2010-2011 «create» hello_jsp.class Source: Web Component Development Wth Servlet and JSP Technologies. Sun Microsystems (course SL-314-EE5) 74 © The Authors 37 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) Communication Software 2010-2011 75 © The Authors 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, Communication Software 2010-2011 – point of access to page attributes – corresponds to the context of the servlet instance 76 © The Authors 38 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 --%> Communication Software 2010-2011 77 © The Authors 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: Communication Software 2010-2011 <%! code %> – declarations inserted into servlet class body, outside of existing methods – e.g. <%! int i=0; %> 78 © The Authors 39 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: Communication Software 2010-2011 Thanks for ordering <%= request.getParameter("title") %> 79 © The Authors Example 1: Expressions Communication Software 2010-2011 // 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> 80 © The Authors 40 Example 1: Server Response Communication Software 2010-2011 81 © The Authors 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 Communication Software 2010-2011 <% if (Math.random() < 0.5) { %> <p>Have a <b>nice</b> day!</p> <% } else { %> <p>Have a <b>lousy</b> day!</p> <% } %> 82 © The Authors 41 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> Communication Software 2010-2011 83 © The Authors 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> Communication Software 2010-2011 84 © The Authors 42 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> Communication Software 2010-2011 85 © The Authors 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 Communication Software 2010-2011 86 © The Authors 43 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 Communication Software 2010-2011 87 © The Authors Attributes of the page Directive Communication Software 2010-2011 • • • • • • • • • • • import contentType isThreadSafe session buffer autoflush extends info errorPage isErrorPage language 88 © The Authors 44 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.*" %> Communication Software 2010-2011 89 © The Authors page Directive: contentType Attribute • Sets the Content-Type response header <%@ page contentType="MIME-Type" %> <%@ page contentType="MIME-Type; charset=Character-Set" %> • Example <%@ page contentType="text/html; charset=ISO-8859-1" %> Communication Software 2010-2011 90 © The Authors 45 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 Communication Software 2010-2011 91 © The Authors 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 Communication Software 2010-2011 – JSP files • that use the tag library 92 © The Authors 46 Actions < jsp:action attributes > • Tags interpreted at execution time – jsp:include – jsp:forward – jsp:param Communication Software 2010-2011 – jsp:useBean – jsp:setProperty – jsp:getProperty JavaBeans tags – jsp:plugin – jsp:params – jsp:fallback HTML <object> tags 93 © The Authors 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 Communication Software 2010-2011 • thus, URL may point to JSP or servlets 94 © The Authors 47 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: Communication Software 2010-2011 <jsp:forward page="list.jsp" /> 95 © The Authors 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: Communication Software 2010-2011 <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> 96 © The Authors 48 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 Communication Software 2010-2011 <jsp:text> text </jsp:text> 97 © The Authors 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> Communication Software 2010-2011 </body> </html> 98 © The Authors 49 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"); . . . Communication Software 2010-2011 } } 99 © The Authors 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 Communication Software 2010-2011 100 © The Authors 50 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 Communication Software 2010-2011 – property editors 101 © The Authors 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 Communication Software 2010-2011 102 © The Authors 51 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() %> • Communication Software 2010-2011 Assigning to properties: <jsp:setProperty name="book1" property="title" value="Bible" /> is equivalent to: <%= book1.setTitle("Bible") %> 103 © The Authors 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? Communication Software 2010-2011 – explicit type conversion (inside try-catch), but… … see next slide 104 © The Authors 52 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="*" /> Communication Software 2010-2011 • In these cases, type conversion is automatic 105 © The Authors 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; } } Communication Software 2010-2011 106 © The Authors 53 Example 5: JSP Including Simple Bean Communication Software 2010-2011 © The Authors <!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> 107 </html> Example 5: Server Response Communication Software 2010-2011 108 © The Authors 54 Bean Scope • In the JSP context – beans created with jsp:useBean – bound to a local variable – four possibilities regarding their storage location • scope attribute Communication Software 2010-2011 109 © The Authors 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 Communication Software 2010-2011 – stored in the ServletContext object – accessible through predefined variable application 110 © The Authors 55 Bean Scope Communication Software 2010-2011 111 © The Authors 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 Communication Software 2010-2011 112 © The Authors 56 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!"); Communication Software 2010-2011 – use attribute in JSP (four scopes searched for attribute): <h2>${endMessage}</h2> 113 © The Authors 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: Area Communication Software 2010-2011 URI Prefix Core http://java.sun.com/jsp/jstl/core 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 114 © The Authors 57 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}"] /> Communication Software 2010-2011 115 © The Authors 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 – iteration over the content of the tag <c:forEach items="collection" [var="varName"] [ … ]> body content </c:forEach> • out Communication Software 2010-2011 – evaluates an expression and writes results in current JSPWriter <c:out value="value" [default="defaultValue"] [escapeXml="{true|false}"] /> 116 © The Authors 58 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> Communication Software 2010-2011 previously previously stored stored in in one one of of the the objects: objects: pageContext pageContext,, request request,, session session,, or or application application © The Authors Contents 1. Java Servlets – – – – – introduction the servlet API; interfaces classes and methods HTTP servlets forwarding and including session tracking and session management 2. JavaServer Pages (JSPs) – – – – – introduction predefined variables scripts, directives and actions JSPs and java beans JSP 2.0, JSTL and EL 3. Integration of Servlets and JSPs Communication Software 2010-2011 – – – joint use of servlets and JSPs forwarding in servlets and JSPs the MVC design pattern © The Authors 59 Joint Use of Servlets and JSPs (1/2) • 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 Communication Software 2010-2011 119 © The Authors Joint Use of Servlets and JSPs (2/2) • 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 • Communication Software 2010-2011 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 120 © The Authors 60 Forwarding in Servlets and JSPs • From a JSP (unusual) LoginServlet 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 LoginServlet?login=pepe Communication Software 2010-2011 121 © The Authors 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); Communication Software 2010-2011 } 122 © The Authors 61 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 Communication Software 2010-2011 – handles the request – decides what logic to invoke – decides which view applies 123 © The Authors MVC Pattern: More Detail Source: Java BluePrints, Model-View-Controller. Available at: http://java.sun.com/blueprints/patterns/MVC-detailed.html Communication Software 2010-2011 124 © The Authors 62 MVC is an Architectural Pattern Web server HTTP request Container Client Controller Browser HTTP <% %> HTTP response view Database Source: Web Component Development Wth Servlet and JSP Technologies Sun Microsystems (course SL-314-EE5) Communication Software 2010-2011 Also denoted “Model 2” 125 © The Authors Implementing MVC with Request Dispatcher 1. Define beans to represent the data 2. Servlet handles requests – reads request params & checks for missing/malformed data 3. Servlet populates beans – servlet invokes business logic / data-access code (simple cases: may be bean methods); obtains results – results stored in beans (only servlet creates and modifies beans) 4. Servlet stores beans – invokes setAttribute on request, session or context 5. Servlet forwards request to appropriate JSP page – uses forward method of request dispatcher 6. JSP extracts data from beans Communication Software 2010-2011 – uses jsp:usebean and jsp:getProperty – or uses JSP 2.0 EL: more powerful, concise, readable 126 © The Authors 63 Implementing MVC 3 2 4 5 6 Source: IBM Labs. JSP – Dynamic Content Generation Made Simple Communication Software 2010-2011 127 © The Authors Example: Web Application with JSP • Using only JSP if (login,failed) then forward() POST(login,password) login.jsp forward() validate_login.jsp welcome.jsp • For larger web applications, use MVC: – JSP for the presentation – servlets for the logic Communication Software 2010-2011 128 © The Authors 64 Example: Web Application using MVC if (login failed) then forward(login) POST(login,password) login.jsp login servlet if (not logged) then forward() session.setAttribute(UserInfoBean) forward(ProductBean) list.jsp forward(ListBean) product servlet welcome.jsp GET() GET(productId) Communication Software 2010-2011 DB 129 © The Authors Handling Beans in Servlets and JSPs • JSP: <!–- instantiate/use bean --> <jsp:useBean id='user' class='UserInfoBean' scope='session'> <jsp:setProperty name='user' property='lastName' value='Perez' /> </jsp:useBean> <!–- set property --> <jsp:setProperty name='user' property='firstName' value='Pepe'> <!–- get property --> <jsp:getProperty name='user' property='firstName' /> • Servlet: Communication Software 2010-2011 // instantiate/use bean UserInfoBean user = (UserInfoBean) session.getAttribute("user"); if (user == null) { user = new UserInfoBean(); user.setLastName("Perez"); session.setAttribute("user", user); } // set property user.setFirstName = "Pepe"; // get property out.println(user.getFirstName()); 130 © The Authors 65 MVC: Handling Beans in JSPs • MVC: bean is initialised in servlet and used in JSP – using bean in JSP without the EL: <!–- use bean --> <jsp:useBean id='user' class='UserInfoBean' scope='session' /> <!–- get property --> <jsp:getProperty name='user' property='firstName' /> – using bean in JSP with JSTL EL <!–- use bean and get property --> <c:out value="${user.firstname}" /> – using bean in JSP with JSP 2.0 EL: <!–- use bean and get property --> ${user.firstname} Communication Software 2010-2011 131 © The Authors MVC: Passing Data on Forward • Destination obtains unprocessed info from request object, but – programming easier in origin servlet than destination JSP – multiple JSPs may require the same data • Simple value: pass as attribute of request object, e.g. – at origin request.setAttribute(“key1”, value1); – at target Type1 value1 = (Type1) request.getAttribute(“key1”); or as parameter of forward action • Complex value: represent as shared bean – scope = application: stored in servletContext object – scope = session: stored in session object Communication Software 2010-2011 – scope = request: stored in request object 132 © The Authors 66 Other Topics of Interest • Lifecycle listeners: – monitor and react to events in a servlet's life cycle • Filtering API: Filter, FilterChain, FilterConfig – filter: an object that can transform the header and content (or both) of a request or response (from servlet 2.3) – authentication, logging, image conversion, data compression, encryption, tokenizing streams, XML transformations,… • Java Server Faces – Java/JSP-based Web application framework that simplifies the development of user interfaces for Java EE applications • Jakarta Struts – open-source framework that extends the Java Servlet API to facilitate development of Web applications conforming to the MVC pattern. Communication Software 2010-2011 133 © The Authors On-line Bibliography • Sun's servlet pages / JSP pages / JSTL pages http://java.sun.com/products/servlet/ http://java.sun.com/products/jsp/ http://java.sun.com/products/jsp/jstl/ • Marty Hall's book Core Servlets and JavaServer Pages, vol. 1, 2nd edition • Marty Hall's book More Servlets and JavaServer Pages, 1st edition (including information on filters and lifecycle listeners) • Marty Hall's slides Beginning and Intermediate-Level Servlet, JSP and JDBC Tutorials http://pdf.coreservlets.com/ http://pdf.moreservlets.com/ http://courses.coreservlets.com/Course-Materials/csajsp2.html • Apache Tomcat home page / Marty Hall's Apache Tomcat tutorial http://tomcat.apache.org/ http://www.coreservlets.com/Apache-Tomcat-Tutorial/ • Sun's Java Server Faces Technology pages • Jakarta Struts http://java.sun.com/javaee/javaserverfaces/ Communication Software 2010-2011 http://struts.apache.org/ 134 © The Authors 67