Download presentation
Presentation is loading. Please wait.
1
EE448: Server-Side Development Slide 1 EE448: Server-Side Development Lecturer: David Molloy Time: Tuesdays 3pm-5pm Notes: http://wiki.eeng.dcu.ie/ee448http://wiki.eeng.dcu.ie/ee448 Mailing List: ee448@list.dcu.ieee448@list.dcu.ie
2
EE448: Server-Side Development Slide 2 Session Tracking Session tracking is the capability of the server to maintain the current state of a single client’s sequential requests HTTP is stateless -> how do you keep track of client request sequences? Sites such as those with shopping carts need this capability Why not simply use the client’s IP address as identification? Xterm, proxy servers, multiple browsers etc. Therefore, we get client to introduce itself as it makes each request. Client provides a unique identifier that lets the server identify it. Several different ways of managing session tracking: - User Authorization - Hidden Form Fields - URL Rewriting - Persistent Cookies - Session Tracking API
3
EE448: Server-Side Development Slide 3 User Authorization Most application/web servers have some built in-system for user authorization Apache user authorization used to access module notes Tomcat provides functionality to require clients to login Example: Tomcat Manager Application String name = req.getRemoteUser(); // after authorization + Easy to Implement + Works if user accesses the site from an alternate machine or browser - Users must pre-register for A/C - Users must always log in each time - Can’t simultaneously maintain more than one session at same site - Unsuitable for anonymous session tracking
4
EE448: Server-Side Development Slide 4 Hidden Form Fields One of the simplest methods for session tracking Use standard form fields, which are not displayed to the client Parameters passed back to server, when form is submitted No different between a hidden and visible field (at server end!) Work through example hidden_example.html http://localhost:8080/student/hidden_example.html We pass information from Form to Form -> effectively session tracking Shopping cart this way would pass user id, quantities and item ids from form to form
5
EE448: Server-Side Development Slide 5 Hidden Form Fields + Easy to Implement + Supported by all popular browsers + Users need not log in (server can generate unique IDs) - As quantity of information increases, process becomes tedious (unless persistent information is kept on server, and ID only passed) - Only functions for series of forms (static pages break the process) - Browser shutdown/changing will break the process Advantages Disadvantages
6
EE448: Server-Side Development Slide 6 URL ReWriting Every local URL the user might click is dynamically modified, or rewritten to include extra information Typically, only a unique session ID is passed (256 characters max) Different ways of passing the extra information: Original: http://server:port/context/servlet/ServletNamehttp://server:port/context/servlet/ServletName http://server:port/context/servlet/ServletName/ABCD1234 (path)http://server:port/context/servlet/ServletName/ABCD1234 http://server:port/context/servlet/ServletName?sessionid=ABCD1234 (parameter) Path information method works for both GET and POST Extra Parameter method does not work for POST method Work through: http://localhost:8080/student/servlet/URLRewriting
7
EE448: Server-Side Development Slide 7 URL Rewriting + Easy to Implement + Supported by all popular browsers + Users need not log in (server can generate unique IDs) + URL rewriting works for all dynamically created documents (not just forms!) - Only small quantities of information can be rewritten into URLs (therefore would need server-side persistence) - Typically, URL rewriting does not work for static documents - Browser shutdown breaks the process - Can be very tedious and need to be careful to find all links etc. Advantages Disadvantages
8
EE448: Server-Side Development Slide 8 Persistent/Non Persistent Cookies Cookie = a simple piece of information stored on the client, on behalf of the server When a browser receives a cookie, it saves the cookie on the local hard drive. Expiry for the cookie can be set -> otherwise deleted at browser shutdown Each subsequent visit to the same site, browser sends cookie back to the server with each request Cookie can be used to store a user ID Cookies -> Security Issues? Few k bytes – non-executable Cookies not part of original HTTP specification -> introducted in Netscape and have become a ‘de-facto’ standard
9
EE448: Server-Side Development Slide 9 Persistent/Non-Persistent Cookies Servlet API provides javax.servlet.http.Cookie for using cookies public Cookie (String name, String value) public void HttpServletResponse.addCookie(Cookie cookie) Example: Cookie cookie = new Cookie("userid", "david_molloy832"); cookie.setMaxAge(7200); // 2 hour expiry res.addCookie(cookie); Servlet retrieves cookies by calling the getCookies() method Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i=0; i< cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); }
10
EE448: Server-Side Development Slide 10 Persistent Cookies + Efficient and simple way of session tracking + Exist even if browsers and/or servers are shutdown/restarted + Users need not log on (server can generate Ids) + Works for all documents/pages – even static HTML + Cookes are customizable and powerful - Major problem is that clients sometimes configure browsers to refuse cookies (for security concerns) - If client refuses cookies, you must fall back on another solution Advantages Disadvantages
11
EE448: Server-Side Development Slide 11 Session Tracking API Fortunately, the Servlet API has built-in support for session tracking Session tracking should be supported by any web server that supports servlets To create a new session, you use the HttpServletRequest object’s getSession() method public HttpSession HttpServletRequest.getSession(boolean create); Eg. HttpSession session = req.getSession(true); Method returns the current session associated with the user making the request. If the user has no current valid session, this method creates one if ‘create’ is set as true, or returns null if ‘create’ is false
12
EE448: Server-Side Development Slide 12 Session Tracking API HttpSession object has five methods we are concerned with: - public void setAttribute(String name, Object value) Binds a name/value pair to store in the current session If the name exists, then it is replaced Note: You can store an object, rather than just a String! - public Object getAttribute(String name) Used to get an object stored in the session - public Enumeration getAttributeNames() Returns an Enumeration of all the current bound names stored in the session - public void removeAttribute(String name) Allows the removal of an object from the session - public void invalidate() Can manually invalidate their session and all information
13
EE448: Server-Side Development Slide 13 Session Tracking API Demonstrate the SessionCount servlet Sessions have a limited lifespan (purposefully!) Automatic or manual invalidation (such as logouts) When a user accesses a site, that user is assigned a new HttpSession object and a unique session ID. Session ID is unique and identifies the user The session ID is saved on the client in a cookie or sent as part of a rewritten URL Every server that supports servlets should implement at least cookie-based session tracking (using persistent cookies) Most servers support session tracking based on URL rewriting also
14
EE448: Server-Side Development Slide 14 Session Tracking API + Very efficient and simple way to implement session tracking + Session information can persist (server specific) even with server shutdown/restart + Users need not log on (server generates unique IDs) + Works for all documents/pages, including static HTML + Standardized and included in J2EE + Sessions can be set to “time-out” at user configurable times + Objects stored rather than just strings - Restricted to one browser and tracking lost if browser shuts down or crashes - Slightly more difficult if clients have cookies disabled Advantages Disadvantages
15
EE448: Server-Side Development Slide 15 JavaServer Pages (JSPs) Allow web developers and designers to develop and maintain platform-independent, dynamic web pages for business systems User interface is seperated from content generation Designers can alter overall page layout without altering the underlying dynamic content JSPs make use of XML-like tags and scriptlets written in Java to generate dynamic content JSP like an inside-out servlet! Work through Hello World example
16
EE448: Server-Side Development Slide 16 JavaServer Pages (JSPs) Hello World Example JSP Hello World Example
17
EE448: Server-Side Development Slide 17 Behind the Scenes JSP page is executed by a JSP engine/container, such as Tomcat JSP is actually just a servlet that is mapped to *.jsp JSP Container receives requests to a JSP and generates response When server receives a request it recognises the.jsp extension and begins special handling First time JSP is requested, it is compiled into a servlet object and stored in memory -> output of servlet sent back to user
18
EE448: Server-Side Development Slide 18 Behind the Scenes Subsequent calls to the JSP in the server cache increases the speed of response First call to JSP includes the time necessary for the server to create and compile the background servlet If the.jsp file has not changed since previous request, the server invokes the previously compiled servlet object Provide an example of a JSP error
19
EE448: Server-Side Development Slide 19 Web Application Structure JSP pages share the “Write Once, Run Anywhere” characteristic of Java technology -> typically packaged within the WAR
20
EE448: Server-Side Development Slide 20 Features of JSP Pages Java Based – benefit from all of the Java language benefits Reusable - O/S, platform independent, can write JSPs as components and reuse in different ways for different functionality Seperation of Business Logic and Presentation – web designers can edit and work on HTML while leaving dynamic content alone Large Community Support – JSPs are based on a broad spectrum of industry input and support Platform Independent – write once, run anywhere Ease of Development – non-programmers can use simple JSP specific code for simple tasks, especially by using JavaBeans Portability – JSPs are part of the Web Application Structure, so can be ported easily to alternate application servers
21
EE448: Server-Side Development Slide 21 JSPs & JavaBeans JavaBeans is a portable, platform-independent component model written in Java JavaBeans are small, reusable, software components They deliver functionality to various applications that need such functionality A JavaBean component can be run anywhere Eg. On a client within an AWT component or within a JSP on a server JavaBeans are based on the concept of components, but are not regarded as such by J2EE (it recognises EJBs) JavaBeans are intraprocess components that live at one location, such as GUI components, buttons, tables etc. – small grained application pieces Enterprise JavaBeans are interprocess components that live in multiple address spaces as distributed objects -> later in module
22
EE448: Server-Side Development Slide 22 JavaBeans Examples GUI software components such as push buttons or more complicated like spreadsheets Individual components can be nested and arbitrarily complex Eg. A calculator JavaBean could be built from button JavaBeans etc.
23
EE448: Server-Side Development Slide 23 Sample JavaBean package dave; public class SimpleBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; }
24
EE448: Server-Side Development Slide 24 JSP using JavaBean JavaBean has no main method. To use it we use the tag, as follows: Reusing JavaBeans in JSP Message:
25
EE448: Server-Side Development Slide 25 JSP Syntax HTML Comments Hidden Comments JSP Directives Used to define and set attributes that apply to the entire JSP page 1. include 2. page 3. taglib
26
EE448: Server-Side Development Slide 26 JSP Syntax 1. include Directive Used to instruct the JSP container to insert text into a JSP page at translation time Included file can be a HTML file, JSP file, text file, or a Java code file eg. Work through example DateTime.jsp / JSPInclude.jsp
27
EE448: Server-Side Development Slide 27 JSP Syntax 2. page Directive Page directive is used to define one or more attributes for the whole JSP page. Can be placed anywhere in the JSP file and still apply There are a number of separate page directive attributes: import specifies in a comma-seperated list, the Java packages that the JSP file should import session can be set to true if the client must join a session in order to use the JSP page
28
EE448: Server-Side Development Slide 28 contentType defines the MIME type for the response. Can use any valid types supported by the JSP container. Defaults to text/html extends – the fully qualified name of the superclass of this JSP language=“Scripting Language” Multiple scripting languages may be used in JSP files if supported. The default value is Java.
29
EE448: Server-Side Development Slide 29 3. taglib Directive Taglib directive supported since JSP Version 1.1 Allows JSP authors to define their own tags directive declares that the JSP file uses custom tags, names the tag library that defines them and specifies their prefix Not concerned with taglib any further in this module
30
EE448: Server-Side Development Slide 30 Scripting Elements JSP scripting elements allow Java code to be inserted into the servlet that will be generated from the defined JSP page 3 types of scripting elements: 1.Declarations 2.Scriptlets 3.Expressions
31
EE448: Server-Side Development Slide 31 Declarations JSP declaration allows definition of methods or variables Declared variables and methods have class scope and are available throughout the JSP page Variable declarations must be made before you use them in your JSP file Syntax = Examples:
32
EE448: Server-Side Development Slide 32 Scriptlets Scriptlets provide the ability to directly insert code into an HTML document. Scriptlets can contain any code that is valid based on the language specified in the language directive Java code in our module only A scriptlet is a block of Java code embedded in the service() method of a compiled servlet -> The code is executed on every client’s request for the JSP Any number of scriptlets can appear within a JSP page Syntax:
33
EE448: Server-Side Development Slide 33 Scriptlets Eg. JSP Scriptlet Example View the output in Scriptlet.jsp
34
EE448: Server-Side Development Slide 34 Scriptlets There are four implicit variables automatically available to a JSP file: 1. request – reference to the HttpServletRequest object 2. response – reference to the HttpServletResponse object 3. in – reference to the BufferedReader object that is part of the client request 4. out – reference to the PrintWriter object sent to the client Allows us in particular to handle client interaction
35
EE448: Server-Side Development Slide 35 Scriptlets Example of form interaction: JSP Form Example <% out.println("Your value for parameter A = " + request.getParameter("a")); out.println(" Your value for parameter B = " + request.getParameter("b")); %> Demonstrate SimpleForm.jsp w/o/with parameters
36
EE448: Server-Side Development Slide 36 Expressions Expression element contains an expression that is valid in the scripting language used They are like single-line scriptlets An expression is a tag, that will be replaced by the value of the evaluated expression Value is evaluated, converted to a string, and inserted where the expression occurs in the JSP file Syntax: Example: The current time is: Your IP address is:
37
EE448: Server-Side Development Slide 37 Examples Work through examples from notes JSP Database Connectivity JSP applications like servlets connect to databases using JDBC Covered later in the module
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.