Download presentation
Presentation is loading. Please wait.
Published byArabella Fisher Modified over 8 years ago
1
Net-centric Computing Servlets & JSP
2
Lecture Outline Tracking Sessions Cookies Examples JSP Differences between JSP and Servlets JSP Constructs Examples
3
Sessions Many interactive Web sites spread user data entry out over several pages: – Ex: add items to cart, enter shipping information, enter billing information Problem: how does the server know which users generated which HTTP requests? – Cannot rely on standard HTTP headers to identify a user
4
HTTP is a stateless protocol and cannot be used to maintain data across two sessions To track sessions data in servlets, following techniques can be used: URL rewriting Hidden form fields Cookies Using the HTTPSession interface Tracking Sessions in Servlets
5
Sessions
6
Sessions Server sends back new unique session ID when the request has none
7
Sessions Client that supports session stores the ID and sends it back to the server in subsequent requests
8
Sessions Server knows that all of these requests are from the same client. The set of requests is known as a session.
9
Sessions And the server knows that all of these requests are from a different client.
10
Sessions Returns HttpSession object associated with this HTTP request. Creates new HttpSession object if no session ID in request or no object with this ID exists Otherwise, returns previously created object
11
Sessions Boolean indicating whether returned object was newly created or already existed.
12
Sessions Incremented once per session
13
Sessions Three web pages produced by a single servlet
14
Sessions
15
Sessions
16
Sessions
17
Sessions
18
Sessions,,,
19
Sessions Session attribute is a name/value pair
20
Sessions,,, Session attribute will have null value until a value is assigned
21
Sessions,,, Generate sign-in form if session is new or signIn attribute has no value, weclome-back page otherwise.
22
Sessions Sign-in form Welcome-back page
23
Sessions Second argument (“Greeting”) used as action attribute value (relative URL)
24
Sessions Form will be sent using POST HTTP method ( doPost() method will be called)
25
Sessions Text field containing user name is named signIn
26
Sessions …
27
Sessions … Retrieve signIn parameter value
28
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions … Normal processing: signIn parameter is present in HTTP request
29
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions … Generate HTML for response
30
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions Thank-you page Must escape XML special characters in user input
31
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions … Assign a value to the signIn session attribute
32
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions Session attribute methods: – setAttribute(String name, Object value) : creates a session attribute with the given name and value – Object getAttribute(String name) : returns the value of the session attribute named name, or returns null if this session does not have an attribute with this name
33
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions … Error processing (return user to sign-in form)
34
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Sessions By default, each session expires if a server- determined length of time elapses between a session’s HTTP requests – Server destroys the corresponding session object Servlet code can: – Terminate a session by calling invalidate() method on session object – Set the expiration time-out duration (secs) by calling setMaxInactiveInterval(int)
35
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies A cookie is a name/value pair in the Set-Cookie header field of an HTTP response Most (not all) clients will: – Store each cookie received in its file system – Send each cookie back to the server that sent it as part of the Cookie header field of subsequent HTTP requests
36
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Tomcat sends session ID as value of cookie named JSESSIONID
37
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Cookie-enabled browser returns session ID as value of cookie named JSESSIONID
38
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Servlets can set cookies explicitly – Cookie class used to represent cookies – request.getCookies() returns an array of Cookie instances representing cookie data in HTTP request – response.addCookie(Cookie) adds a cookie to the HTTP response
39
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Cookies are expired by client (server can request expiration date)
40
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies
41
Cookies Return array of cookies contained in HTTP request
42
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Search for cookie named COUNT and extract value as an int
43
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies
44
Cookies Send replacement cookie value to client (overwrites existing cookie)
45
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Should call addCookie() before writing HTML
46
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Privacy issues Client Web site providing requested content HTTP request to intended site HTTP response: HTML document including ad Web site providing banner ads HTTP request for ad image Image plus Set-Cookie in response: third-party cookie
47
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Web site providing requested content Cookies Privacy issues Client Second Web site providing requested content HTTP request to 2nd intended site HTTP response: HTML document including ad Web site providing banner ads HTTP request for ad image plus Cookie (identifies user) Image Based on Referer, I know two Web sites that this user has visited
48
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 Cookies Privacy issues Due to privacy concerns, many users block cookies – Blocking may be fine-tuned. Ex: Mozilla allows Blocking of third-party cookies Blocking based on on-line privacy policy Alternative to cookies for maintaining session: URL rewriting
49
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Tomcat adds session ID within HTML document to all URL’s referring to the servlet Session ID = 4235
50
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Subsequent request will contain session ID in the URL of the request Session ID = 4235
51
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Next response must again add session ID to all URL’s Session ID = 4235
52
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Original (relative) URL: href=“URLEncodedGreeting” URL containing session ID: href=“URLEncodedGreeting;jsessionid=0157B9E85” Path parameter is treated differently than query string parameter – Ex: invisible to getParameter() Path parameter
53
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting HttpServletResponse method encodeURL() will add session id path parameter to argument URL Relative URL of servlet Original servlet Servlet using URL rewriting
54
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Must rewrite every servlet URL in every document Security issues Web site using URL rewriting User A URL with session ID 7152
55
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Must rewrite every servlet URL in every document Security issues Web site using URL rewriting User A User B Email URL URL with session ID 7152
56
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0- 13-185603-0 URL Rewriting Must rewrite every servlet URL in every document Security issues Web site using URL rewriting User A URL with session ID 7152 User B Email URL Visit Web site with session ID 7152
57
Servlets: ― Consist of an HTML file for static content and a Java file for dynamic content ― Require recompilation if changes are made to any of the files ― Involve extensive code writing JSP: ― Contains Java code embedded directly into an HTML page by using special tags ― Automatically incorporates changes made to any files ― Facilitates independent working of Web developers and Web designers Servlets vs JSP
58
JSP Request-Response Cycle
59
JSP Constructs Three scripting constructs: expressions scriplets declarations
60
JSP Expressions Is used to insert a Java expression directly into the output Has the following form: The expression is evaluated, converted into a string, and sent to the output stream of the servlet
61
JSP Scriplets Enables us to insert a Java statement into the servlet’s jspService method, which is invoked by the service method Has the following form:
62
JSP Declarations Is used to declare methods or fields into the servlet Has the following form:
63
JSP Comments Has the following form:
64
Example Computing Factorials Factorial Factorial of is <%! private long computeFactorial(int n) { if (n == 0) return 1; else return n * computeFactorial(n - 1); } %> JSP scriptlet JSP expression JSP declaration
65
JSP Predefined Variables Can be used with JSP expressions and scriplets. They are eight of them: request response out session application config pagecontext page
66
66 Example Computing Loan Write an HTML page that prompts the user to enter loan amount, annual interest rate, and number of years. Clicking the Compute Loan Payment button invokes a JSP to compute and display the monthly and total loan payment. ComputeLoan Compute Loan Payment <form method="get" action="http://localhost:8080/examples/jsp/ComputeLoan.jsp"> Loan Amount Annual Interest Rate Number of Years
67
67 ComputeLoan <% double loanAmount = Double.parseDouble( request.getParameter("loanAmount")); double annualInterestRate = Double.parseDouble( request.getParameter("annualInterestRate")); double numberOfYears = Integer.parseInt( request.getParameter("numberOfYears")); double monthlyInterestRate = annualInterestRate / 1200; double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; %> Loan Amount: Annual Interest Rate: Number of Years: Monthly Payment: Total Payment: Predefined variable
68
JSP Directives Messages to the JSP Container and do not produce output into the current output stream Syntax, or <%@ directive attribute1="value1" attribute2="value2" … %>
69
JSP Directives They are three of them: page: provide information for the page such as importing classes and setting up content type include: insert a file to the servlet, must be placed where we want the file to be inserted tablib: define custom tags
70
70 Example: Using Error Pages This example prompts the user to enter an integer and displays the factorial for the integer. If a noninteger value is entered by mistake, an error page is displayed.
71
71 FactorialInput <FORM method="post" action="http://localhost:8080/examples/jsp/ComputeFactorial.jsp"> Enter an integer
72
72 ComputeFactorial <% NumberFormat format = NumberFormat.getNumberInstance(); int number = Integer.parseInt(request.getParameter("number")); %> Factorial of is <%! private long computeFactorial(int n) { if (n == 0) return 1; else return n * computeFactorial(n - 1); } %> Error page
73
73 FactorialInputError Error -- Input is not an integer. Indicate it is error page
74
74 JSP in XML JSP can be embedded in XML as well as in HTML Due to XML’s syntax rules, the tags must be different (but they do the same things) HTML: XML: expression HTML: XML: code HTML: XML: declarations HTML: XML:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.