The Presentation Tier of the Java EE Architecture
|
|
- Madeline Stanley
- 6 years ago
- Views:
Transcription
1 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 Part I, chapters 1-5, 8-11,
2 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
3 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
4 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
5 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
6 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
7 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
8 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
9 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>admin </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
10 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
11 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
12 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
13 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
14 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
15 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
16 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\" " + "\" >\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
17 HTTPServletRequest interface Reading HTML Form Data from Servlets 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) 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
18 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\"" + " \" public static String headwithtitle (String title) return(doctype + "\n" + "<html>\n" + "<head><title>" + title + "</title></head>\n"); } } 36 18
19 Example 3: HTML Form <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " <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
20 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
21 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
22 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
23 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
24 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: String getprotocol() returns the name and version of the protocol in the form: protocol/majorversion.minorversion example: HTTP/
25 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
26 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
27 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
28 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(" } else { } sendloginform(response, true); } } response.senderror(response.sc_forbidden, "Login Failed"); 56 28
29 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
30 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(" rd.forward(request, response); } else { sendloginform(response, true); } } 60 30
31 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
32 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 ! 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
33 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
34 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
35 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
36 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 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
37 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 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
38 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
39 JSP Processing hello.jsp <% Web server hello_jsp.java %> 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
40 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
41 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: response: Thanks for ordering <%= request.getparameter("title") %> 82 41
42 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
43 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
44 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
45 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
46 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
47 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 " %> 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
48 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
49 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
50 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>
51 Example 4: Simple JSP page language= java contenttype= text/html;charset=iso %> 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 "); 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");
52 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
53 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") %>
54 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=" " param="new_ " /> is equivalent to customer.set (request.getparameter("new_ ") parameter and property have identical names: <jsp:setproperty name="customer" property=" " /> is equivalent to customer.set (request.getparameter(" ") Associating values of all properties with identically-named request parameters: <jsp:setproperty name="customer" property="*" /> In these cases, type conversion is automatic
55 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
56 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
57 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
58 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>
59 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 Prefix c XML processing x Formatting / internationalisation fmt Relational database access sql 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}"] />
60 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=" 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
61 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
62 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
63 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);
64 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:
COMP9321 Web Application Engineering
COMP9321 Web Application Engineering Java Server Pages (JSP) Dr. Basem Suleiman Service Oriented Computing Group, CSE, UNSW Australia Semester 1, 2016, Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2442
More informationAdvanced Internet Technology Lab # 5 Handling Client Requests
Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2011 Advanced Internet Technology Lab # 5 Handling Client Requests Eng. Doaa Abu Jabal Advanced Internet Technology Lab
More informationCOMP9321 Web Application Engineering
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2411 1 Review:
More informationServlet Fudamentals. Celsina Bignoli
Servlet Fudamentals Celsina Bignoli bignolic@smccd.net What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications:
More informationJSP Scripting Elements
JSP Scripting Elements Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet and JSP Training Courses: courses.coreservlets.com 1 Slides Marty Hall, http://, book Sun Microsystems
More informationEnterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle
Introduction Now that the concept of servlet is in place, let s move one step further and understand the basic classes and interfaces that java provides to deal with servlets. Java provides a servlet Application
More informationSession 8. Introduction to Servlets. Semester Project
Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the
More informationJava Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1
Java Enterprise Edition Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Beans Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 2 Java Bean POJO class : private Attributes public
More informationServlet Basics. Agenda
Servlet Basics 1 Agenda The basic structure of servlets A simple servlet that generates plain text A servlet that generates HTML Servlets and packages Some utilities that help build HTML The servlet life
More informationHttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently.
More information1. Introduction. 2. Life Cycle Why JSP is preferred over Servlets? 2.1. Translation. Java Server Pages (JSP) THETOPPERSWAY.
1. Introduction Java Server Pages (JSP) THETOPPERSWAY.COM Java Server Pages (JSP) is used for creating dynamic web pages. Java code can be inserted in HTML pages by using JSP tags. The tags are used for
More informationServlets and JSP (Java Server Pages)
Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight,
More informationCOMP9321 Web Application Engineering
COMP9321 Web Application Engineering Semester 2, 2017 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2465 1 Review:
More informationJavaServer Pages (JSP)
JavaServer Pages (JSP) The Context The Presentation Layer of a Web App the graphical (web) user interface frequent design changes usually, dynamically generated HTML pages Should we use servlets? No difficult
More informationSession 20 Data Sharing Session 20 Data Sharing & Cookies
Session 20 Data Sharing & Cookies 1 Reading Shared scopes Java EE 7 Tutorial Section 17.3 Reference http state management www.ietf.org/rfc/rfc2965.txt Cookies Reading & Reference en.wikipedia.org/wiki/http_cookie
More informationUsing JavaBeans with JSP
Using JavaBeans with JSP Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet and JSP Training Courses: courses.coreservlets.com 1 Slides Marty Hall, http://, book Sun Microsystems
More informationPSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming
PSD1B Advance Java Programming Unit : I-V PSD1B- Advance Java Programming 1 UNIT I - SYLLABUS Servlets Client Vs Server Types of Servlets Life Cycle of Servlets Architecture Session Tracking Cookies JDBC
More informationUnit 5 JSP (Java Server Pages)
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. It focuses more on presentation logic
More informationJava Servlets. Preparing your System
Java Servlets Preparing to develop servlets Writing and running an Hello World servlet Servlet Life Cycle Methods The Servlet API Loading and Testing Servlets Preparing your System Locate the file jakarta-tomcat-3.3a.zip
More informationServlet and JSP Review
2006 Marty Hall Servlet and JSP Review A Recap of the Basics 2 JSP, Servlet, Struts, JSF, AJAX, & Java 5 Training: http://courses.coreservlets.com J2EE Books from Sun Press: http://www.coreservlets.com
More informationIntroduction to JSP and Servlets Training 5-days
QWERTYUIOP{ Introduction to JSP and Servlets Training 5-days Introduction to JSP and Servlets training course develops skills in JavaServer Pages, or JSP, which is the standard means of authoring dynamic
More informationSession 9. Introduction to Servlets. Lecture Objectives
Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 10/11/2018 1 Reading & Reference Reading Use the
More informationFast Track to Java EE 5 with Servlets, JSP & JDBC
Duration: 5 days Description Java Enterprise Edition (Java EE 5) is a powerful platform for building web applications. The Java EE platform offers all the advantages of developing in Java plus a comprehensive
More informationJAVA SERVLET. Server-side Programming PROGRAMMING
JAVA SERVLET Server-side Programming PROGRAMMING 1 AGENDA Passing Parameters Session Management Cookie Hidden Form URL Rewriting HttpSession 2 HTML FORMS Form data consists of name, value pairs Values
More informationa. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.
Answers 1. What is the super interface to all the JDBC Drivers, specify their fully qualified name? a. Java.sql.Driver i. JDBC-ODBC Driver ii. Java-Native API Driver iii. All Java Net Driver iv. Java Native
More information01KPS BF Progettazione di applicazioni web
01KPS BF Progettazione di applicazioni web Introduction to Java Server Pages Fulvio Corno, Alessio Bosca Dipartimento di Automatica e Informatica Politecnico di Torino PAW - JSP intro 1 Introduction to
More informationAdvanced Web Technology
Berne University of Applied Sciences Dr. E. Benoist Winter Term 2005-2006 Presentation 1 Presentation of the Course Part Java and the Web Servlet JSP and JSP Deployment The Model View Controler (Java Server
More informationJavaServer Pages. Juan Cruz Kevin Hessels Ian Moon
Page 1 of 14 JavaServer Pages Table of Contents 1. Introduction What is JSP? Alternative Solutions Why Use JSP? 2. JSP Process Request Compilation Example 3. Object Instantiation and Scope Scope Synchronization
More informationThis course is intended for Java programmers who wish to write programs using many of the advanced Java features.
COURSE DESCRIPTION: Advanced Java is a comprehensive study of many advanced Java topics. These include assertions, collection classes, searching and sorting, regular expressions, logging, bit manipulation,
More informationJavaServer Pages. What is JavaServer Pages?
JavaServer Pages SWE 642, Fall 2008 Nick Duan What is JavaServer Pages? JSP is a server-side scripting language in Java for constructing dynamic web pages based on Java Servlet, specifically it contains
More informationServlets. An extension of a web server runs inside a servlet container
Servlets What is a servlet? An extension of a web server runs inside a servlet container A Java class derived from the HttpServlet class A controller in webapplications captures requests can forward requests
More informationAJP. CHAPTER 5: SERVLET -20 marks
1) Draw and explain the life cycle of servlet. (Explanation 3 Marks, Diagram -1 Marks) AJP CHAPTER 5: SERVLET -20 marks Ans : Three methods are central to the life cycle of a servlet. These are init( ),
More informationChapter 10 Servlets and Java Server Pages
Chapter 10 Servlets and Java Server Pages 10.1 Overview of Servlets A servlet is a Java class designed to be run in the context of a special servlet container An instance of the servlet class is instantiated
More informationJava Server Pages. Copyright , Xiaoping Jia. 7-01/54
Java Server Pages What is Java Server Pages (JSP)? HTML or XML pages with embedded Java code to generate dynamic contents. a text-based document that describes how to process a request and to generate
More informationBerner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2
Java Servlets Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist Fall Term 2016-17 Introduction HttpServlets Class HttpServletResponse HttpServletRequest Lifecycle Methods Session Handling
More informationJSP Scripting Elements
2009 Marty Hall Invoking Java Code with JSP Scripting Elements Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/csajsp2.html 2 Customized Java EE Training:
More informationSERVLETS INTERVIEW QUESTIONS
SERVLETS INTERVIEW QUESTIONS http://www.tutorialspoint.com/servlets/servlets_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Servlets Interview Questions have been designed especially
More informationJava servlets CSCI 470: Web Science Keith Vertanen Copyright 2013
Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Overview Dynamic web content genera2on (thus far) CGI Web server modules Server- side scrip2ng e.g. PHP, ASP, JSP Custom web server Java
More informationCSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, JSPs 1
CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, 2004 JSPs 1 As we know, servlets, replacing the traditional CGI technology, can do computation and generate dynamic contents during
More information&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,
! "# # $! " &' ()!"#$$&$'(!!! ($) * + #!,)& - #-& +"- #!(-& #& #$.//0& -#-!& #-$$!& 1+#& 2-2" (3" 3 * * +, - -! #.// HttpServlet $ Servlet 2 $"!4)$5 #& 5 5 6! 0 -.// # 1 7 8 5 9 2 35-4 2 3+ -4 2 36-4 $
More informationModule 4: SERVLET and JSP
1.What Is a Servlet? Module 4: SERVLET and JSP A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper
More informationFast Track to Java EE
Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This
More informationServlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?
What are Servlets? Servlets1 Fatemeh Abbasinejad abbasine@cs.ucdavis.edu A program that runs on a web server acting as middle layer between requests coming from a web browser and databases or applications
More informationUNIT-V. Web Servers: Tomcat Server Installation:
UNIT-V Web Servers: The Web server is meant for keeping Websites. It Stores and transmits web documents (files). It uses the HTTP protocol to connect to other computers and distribute information. Example:
More information1.264 Lecture 15. Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages
1.264 Lecture 15 Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages Development environments XML, WSDL are documents SOAP is HTTP extension UDDI is a directory/registry
More informationINVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Topics in This Chapter
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS Topics in This Chapter Static vs. dynamic text Dynamic code and good JSP design The importance of packages for JSP helper/utility classes JSP expressions
More informationJAVA. Web applications Servlets, JSP
JAVA Web applications Servlets, JSP Overview most of current web pages are dynamic technologies and laguages CGI, PHP, ASP,... now we do not talk about client side dynamism (AJAX,..) core Java-based technologies
More informationCSC309: Introduction to Web Programming. Lecture 10
CSC309: Introduction to Web Programming Lecture 10 Wael Aboulsaadat WebServer - WebApp Communication 2. Servlets Web Browser Get servlet/serv1? key1=val1&key2=val2 Web Server Servlet Engine WebApp1 serv1
More informationCE212 Web Application Programming Part 3
CE212 Web Application Programming Part 3 30/01/2018 CE212 Part 4 1 Servlets 1 A servlet is a Java program running in a server engine containing methods that respond to requests from browsers by generating
More informationQuestions and Answers
Q.1) Servlet mapping defines A. An association between a URL pattern and a servlet B. An association between a URL pattern and a request page C. An association between a URL pattern and a response page
More informationIntroduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web
Introduction to Java Servlets James Baldo Jr. SWE 432 Design and Implementation of Software for the Web Web Applications A web application uses enabling technologies to 1. make web site contents dynamic
More informationUnit 4 Java Server Pages
Q1. List and Explain various stages of JSP life cycle. Briefly give the function of each phase. Ans. 1. A JSP life cycle can be defined as the entire process from its creation till the destruction. 2.
More informationAdvance Java. Configuring and Getting Servlet Init Parameters per servlet
Advance Java Understanding Servlets What are Servlet Components? Web Application Architecture Two tier, three tier and N-tier Arch. Client and Server side Components and their relation Introduction to
More informationWeb based Applications, Tomcat and Servlets - Lab 3 -
CMPUT 391 Database Management Systems Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta The Basic Web Server CMPUT 391 Database Management
More informationServlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil
Servlet And JSP, Government Polytechnic, Ahmednagar Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To write servlet for cookies and session
More informationJSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
http://www.tutorialspoint.com/jsp/jsp_syntax.htm JSP - SYNTAX Copyright tutorialspoint.com This tutorial will give basic idea on simple syntax ie. elements involved with JSP development: The Scriptlet:
More informationJava Server Pages JSP
Java Server Pages JSP Agenda Introduction JSP Architecture Scripting Elements Directives Implicit Objects 2 A way to create dynamic web pages Introduction Separates the graphical design from the dynamic
More information4.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
UNIT - 4 Servlet 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 browser and request the servlet, example
More informationGet the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:
Managing Cookies Cookies Cookies are a general mechanism which server side applications can use to both store and retrieve information on the client side Servers send cookies in the HTTP response and browsers
More informationTable of Contents. Introduction... xxi
Introduction... xxi Chapter 1: Getting Started with Web Applications in Java... 1 Introduction to Web Applications... 2 Benefits of Web Applications... 5 Technologies used in Web Applications... 5 Describing
More informationJAVA SERVLET. Server-side Programming INTRODUCTION
JAVA SERVLET Server-side Programming INTRODUCTION 1 AGENDA Introduction Java Servlet Web/Application Server Servlet Life Cycle Web Application Life Cycle Servlet API Writing Servlet Program Summary 2 INTRODUCTION
More informationServer Side Internet Programming
Server Side Internet Programming DD1335 (Lecture 6) Basic Internet Programming Spring 2010 1 / 53 Server Side Internet Programming Objectives The basics of servlets mapping and configuration compilation
More informationSession 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing
Session 9 Data Sharing & Cookies 1 Reading Reading & Reference Chapter 5, pages 185-204 Reference http state management www.ietf.org/rfc/rfc2109.txt?number=2109 2 3/1/2010 1 Lecture Objectives Understand
More informationA.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>
A JSP A.1 JSP Servlet Java HTML JSP HTML Java ( HTML JSP ) JSP Servlet Servlet HTML JSP MyDate.jsp
More informationThe Structure and Components of
Web Applications The Structure and Components of a JEE Web Application Sample Content garth@ggilmour.com The Structure t of a Web Application The application is deployed in a Web Archive A structured jar
More informationThe Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4
CMPUT 391 Database Management Systems The Basic Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems
More informationBasic Principles of JSPs
5 IN THIS CHAPTER What Is a JSP? Deploying a JSP in Tomcat Elements of a JSP Page Chapter 4, Basic Principles of Servlets, introduced you to simple Web applications using servlets. Although very useful
More informationEnterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets
ID2212 Network Programming with Java Lecture 10 Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets Leif Lindbäck, Vladimir Vlassov KTH/ICT/SCS HT 2015
More informationServlets Basic Operations
Servlets Basic Operations Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring Overview Preparing to
More informationPES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II
PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II Subject Name: Advanced JAVA programming Subject Code: 13MCA42 Time: 11:30-01:00PM Max.Marks: 50M ----------------------------------------------------------------------------------------------------------------
More informationCHAPTER 2: A FAST INTRODUCTION TO BASIC SERVLET PROGRAMMING
Taken from More Servlets and JavaServer Pages by Marty Hall. Published by Prentice Hall PTR. For personal use only; do not redistribute. For a complete online version of the book, please see http://pdf.moreservlets.com/.
More informationUsing JavaBeans Components in JSP Documents
2003-2004 Marty Hall Using JavaBeans Components in JSP Documents 2 JSP and Servlet Training Courses: http://courses.coreservlets.com JSP and Servlet Books from Sun Press: http://www.coreservlets.com 2003-2004
More informationIn servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.
In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter. You can also call request.getparametervalues if the parameter appears more than once,
More informationTo follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-
Ordering Information: Advanced Java 2 Platform How to Program View the complete Table of Contents Read the Preface Download the Code Examples To view all the Deitel products and services available, visit
More informationBuilding Web Applications in WebLogic
Patrick c01.tex V3-09/18/2009 12:15pm Page 1 Building Web Applications in WebLogic Web applications are an important part of the Java Enterprise Edition (Java EE) platform because the Web components are
More informationHTTP and the Dynamic Web
HTTP and the Dynamic Web How does the Web work? The canonical example in your Web browser Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object
More informationDatabase Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실
데이타베이스시스템연구실 Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실 Overview http://www.tutorialspoint.com/jsp/index.htm What is JavaServer Pages? JavaServer Pages (JSP) is a server-side programming
More informationJSP - ACTIONS. There is only one syntax for the Action element, as it conforms to the XML standard:
http://www.tutorialspoint.com/jsp/jsp_actions.htm JSP - ACTIONS Copyright tutorialspoint.com JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
More informationHandling the Client Request: HTTP Request Headers
Handling the Client Request: HTTP Request Headers 1 Agenda Reading HTTP request headers Building a table of all the request headers Understanding the various request headers Reducing download times by
More informationAbout the Authors. Who Should Read This Book. How This Book Is Organized
Acknowledgments p. XXIII About the Authors p. xxiv Introduction p. XXV Who Should Read This Book p. xxvii Volume 2 p. xxvii Distinctive Features p. xxviii How This Book Is Organized p. xxx Conventions
More informationSNS COLLEGE OF ENGINEERING, Coimbatore
SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 04 APPLETS Java applets- Life
More information6- JSP pages. Juan M. Gimeno, Josep M. Ribó. January, 2008
6- JSP pages Juan M. Gimeno, Josep M. Ribó January, 2008 Contents Introduction to web applications with Java technology 1. Introduction. 2. HTTP protocol 3. Servlets 4. Servlet container: Tomcat 5. Web
More informationJSP MOCK TEST JSP MOCK TEST IV
http://www.tutorialspoint.com JSP MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to JSP Framework. You can download these sample mock tests at your local
More informationCSC309: Introduction to Web Programming. Lecture 11
CSC309: Introduction to Web Programming Lecture 11 Wael Aboulsaadat Servlets+JSP Model 2 Architecture 2 Servlets+JSP Model 2 Architecture = MVC Design Pattern 3 Servlets+JSP Model 2 Architecture Controller
More informationWeb Programming. Lecture 11. University of Toronto
CSC309: Introduction to Web Programming Lecture 11 Wael Aboulsaadat University of Toronto Servlets+JSP Model 2 Architecture University of Toronto 2 Servlets+JSP Model 2 Architecture = MVC Design Pattern
More informationADVANCED JAVA TRAINING IN BANGALORE
ADVANCED JAVA TRAINING IN BANGALORE TIB ACADEMY #5/3 BEML LAYOUT, VARATHUR MAIN ROAD KUNDALAHALLI GATE, BANGALORE 560066 PH: +91-9513332301/2302 www.traininginbangalore.com 2EE Training Syllabus Java EE
More informationJava E-Commerce Martin Cooke,
Java E-Commerce Martin Cooke, 2002 1 Java technologies for presentation: JSP Today s lecture in the presentation tier Java Server Pages Tomcat examples Presentation How the web tier interacts with the
More informationHandout 31 Web Design & Development
Lecture 31 Session Tracking We have discussed the importance of session tracking in the previous handout. Now, we ll discover the basic techniques used for session tracking. Cookies are one of these techniques
More informationPrinciples and Techniques of DBMS 6 JSP & Servlet
Principles and Techniques of DBMS 6 JSP & Servlet Haopeng Chen REliable, INtelligent and Scalable Systems Group (REINS) Shanghai Jiao Tong University Shanghai, China http://reins.se.sjtu.edu.cn/~chenhp
More informationADVANCED JAVA COURSE CURRICULUM
ADVANCED JAVA COURSE CURRICULUM Index of Advanced Java Course Content : 1. Basics of Servlet 2. ServletRequest 3. Servlet Collaboration 4. ServletConfig 5. ServletContext 6. Attribute 7. Session Tracking
More informationIntegrating Servlets and JavaServer Pages Lecture 13
Integrating Servlets and JavaServer Pages Lecture 13 Core Servlets & JSP book: More Servlets & JSP book: www.moreservlets.com Servlet and JSP Training Courses: courses.coreservlets.com 1 Slides Marty Hall,
More informationsessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres
sessionx Desarrollo de Aplicaciones en Red José Rafael Rojano Cáceres http://www.uv.mx/rrojano A few more words about Common Gateway Interface 1 2 CGI So originally CGI purpose was to let communicate a
More informationUniversité du Québec à Montréal
Laboratoire de Recherches sur les Technologies du Commerce Électronique arxiv:1803.05253v1 [cs.se] 14 Mar 2018 Université du Québec à Montréal How to Implement Dependencies in Server Pages of JEE Web Applications
More informationThis tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.
About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire
More informationMore JSP. Advanced Topics in Java. Khalid Azim Mughal Version date: ATIJ More JSP 1/42
More JSP Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2006-09-04 ATIJ More JSP 1/42 Overview Including Resources in JSP Pages using the jsp:include
More informationFirst Servlets. Chapter. Topics in This Chapter
First Servlets Chapter Topics in This Chapter The basic structure of servlets A simple servlet that generates plain text The process of compiling, installing, and invoking servlets A servlet that generates
More informationHow 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
How does the Web work? The canonical example in your Web browser and the Dynamic Web Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object on a
More informationTrabalhando com JavaServer Pages (JSP)
Trabalhando com JavaServer Pages (JSP) Sumário 7.2.1 Introdução 7.2.2 JavaServer Pages Overview 7.2.3 First JavaServer Page Example 7.2. Implicit Objects 7.2.5 Scripting 7.2.5.1 Scripting Components 7.2.5.2
More informationJSP. Common patterns
JSP Common patterns Common JSP patterns Page-centric (client-server) CLIENT JSP or Servlet CLIENT Enterprise JavaBeans SERVER DB Common JSP patterns Page-centric 1 (client-server) Page View request response
More informationCOMP201 Java Programming
COMP201 Java Programming Part III: Advanced Features Topic 16: JavaServer Pages (JSP) Servlets and JavaServer Pages (JSP) 1.0: A Tutorial http://www.apl.jhu.edu/~hall/java/servlet-tutorial/servlet-tutorial-intro.html
More information