Download presentation
Presentation is loading. Please wait.
1
Server-side Programming: Java Servlets CSI 3140 WWW Structures, Techniques and Standards
2
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides2 Server-side Programming The combination of HTML JavaScript DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are often called dynamic pages (vs. static)
3
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides3 Server-side Programming Similarly, web server response can be static or dynamic Static: HTML document is retrieved from the file system and returned to the client Dynamic: HTML document is generated by a program in response to an HTTP request Java servlets are one technology for producing dynamic server responses Servlet is a class instantiated by the server to produce a dynamic response
4
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides4 Servlet Overview
5
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides5 Servlet Overview 1.When server starts it instantiates servlets 2.Server receives HTTP request, determines need for dynamic response 3.Server selects the appropriate servlet to generate the response, creates request/response objects, and passes them to a method on the servlet instance 4.Servlet adds information to response object via method calls 5.Server generates HTTP response based on information stored in response object
6
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides6 Hello World! Servlet
7
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides7 Hello World! Servlet All servlets we will write are subclasses of HttpServlet
8
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides8 Hello World! Servlet Server calls doGet() in response to GET request
9
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides9 Hello World! Servlet Interfaces implemented by request/response objects
10
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides10 Hello World! Servlet Production servlet should catch these exceptions
11
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides11 Hello World! Servlet JWSDP Tomcat server exception handling: Stack trace appended to logs/jwsdp_log.*.txt HTML document returned to client may (or may not) contain partial stack trace Servlet output to System.out.print(), printStackTrace(), etc. is appended to logs/launcher.server.log
12
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides12 Hello World! Servlet First two things done by typical servlet; must be in this order
13
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides13 Hello World! Servlet
14
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides14 Hello World! Servlet HTML generated by calling print() or println() on the servlet’s PrintWriter object
15
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides15 Hello World! Servlet Good practice to explicitly close the PrintWriter when done
16
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides16 Servlets vs. Java Applications Servlets do not have a main() The main() is in the server Entry point to servlet code is via call to a method ( doGet() in the example) Servlet interaction with end user is indirect via request/response object APIs Actual HTTP request/response processing is handled by the server Primary servlet output is typically HTML
17
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides17 Running Servlets Simple way to run a servlet (better later): 1. Compile servlet (make sure that JWSDP libraries are on path) 2. Copy.class file to shared/classes directory 3. (Re)start the Tomcat web server 4. If the class is named ServletHello, browse to http://localhost:8080/servlet/ServletHello
18
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides18 Dynamic Content
19
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides19 Dynamic Content
20
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides20 Dynamic Content
21
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides21 Dynamic Content Potential problems: Assuming one instance of servlet on one server, but Many Web sites are distributed over multiple servers Even a single server can (not default) create multiple instances of a single servlet Even if the assumption is correct, this servlet does not handle concurrent accesses properly We’ll deal with this later in the chapter
22
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides22 Servlet Life Cycle Servlet API life cycle methods init() : called when servlet is instantiated; must return before any other methods will be called service() : method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later) destroy() : called when server shuts down
23
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides23 Servlet Life Cycle Example life cycle method: attempt to initialize visits variable from file
24
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides24 Servlet Life Cycle Exception to be thrown if initialization fails and servlet should not be instantiated
25
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides25 Parameter Data The request object (which implements HttpServletRequest ) provides information from the HTTP request to the servlet One type of information is parameter data, which is information from the query string portion of the HTTP request Query string with one parameter
26
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides26 Parameter Data Parameter data is the Web analog of arguments in a method call: Query string syntax and semantics
27
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides27 Parameter Data Query string syntax and semantics Multiple parameters separated by & Order of parameters does not matter All parameter values are strings Value of arg is empty string
28
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides28 Parameter Data Parameter names and values can be any 8-bit characters URL encoding is used to represent non- alphanumeric characters: URL decoding applied by server to retrieve intended name or value Value of arg is ‘a String’
29
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides29 Parameter Data URL encoding algorithm
30
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides30 Parameter Data
31
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides31 Parameter Data
32
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides32 Parameter Data
33
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides33 Parameter Data Must escape XML special characters in all user-supplied data before adding to HTML to avoid cross-site scripting attacks
34
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides34 Parameter Data Cross-site scripting Attacker Blogging Web site Comment containing element Document containing attacker’s comment (and script) Victim
35
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides35 Parameter Data Also need to escape quotes within attribute values.
36
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides36 Parameter Data
37
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides37 Parameter Data A form automatically generates a query string when submitted Parameter name specified by value of name attributes of form controls Parameter value depends on control type Value for checkbox specified by value attribute
38
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides38 Parameter Data
39
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides39 Parameter Data username lifestory boxgroup1 (values same as labels) doit
40
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides40 Parameter Data Query string produced by browser (all one line): Checkbox parameters have same name values; only checked boxes have corresponding parameters
41
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides41 Parameter Data GET vs. POST method for forms: GET: Query string is part of URL Length of query string may be limited Recommended when parameter data is not stored but used only to request information (e.g., search engine query) The URL can be bookmarked or emailed and the same data will be passed to the server when the URL is revisited
42
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides42 Parameter Data Browser content copyright 2004 Google, Inc. Used by permission.
43
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides43 Parameter Data GET vs. POST method for forms: POST: Query string is sent as body of HTTP request Length of query string is unlimited Recommended if parameter data is intended to cause the server to update stored data Most browsers will warn you if they are about to resubmit POST data to avoid duplicate updates
44
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides44 Parameter Data
45
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides45 Parameter Data GET vs. POST in a Web application: According to the HTTP 1.1 specification (RFC 2616): In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval A consequence of this is that “web accelerators” might pre- fetch your GET-based URL, with possible disastrous consequences if you actually use GET for processing. (note that because of this, accelerators such as Google’s won’t pre-fetch GET-based URLs with parameters)
46
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides46 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
47
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides47 Sessions
48
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides48 Sessions Server sends back new unique session ID when the request has none
49
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides49 Sessions Client that supports session stores the ID and sends it back to the server in subsequent requests
50
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides50 Sessions Server knows that all of these requests are from the same client. The set of requests is known as a session.
51
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides51 Sessions And the server knows that all of these requests are from a different client.
52
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides52 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
53
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides53 Sessions Boolean indicating whether returned object was newly created or already existed.
54
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides54 Sessions Incremented once per session
55
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides55 Sessions Three web pages produced by a single servlet
56
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides56 Sessions
57
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides57 Sessions,,,
58
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides58 Sessions,,, Session attribute is a name/value pair
59
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides59 Sessions,,, Session attribute will have null value until a value is assigned
60
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides60 Sessions,,, Generate sign-in form if session is new or signIn attribute has no value, weclome-back page otherwise.
61
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides61 Sessions Sign-in form Welcome-back page
62
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides62 Sessions Second argument (“Greeting”) used as action attribute value (relative URL)
63
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides63 Sessions Form will be sent using POST HTTP method ( doPost() method will be called)
64
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides64 Sessions Text field containing user name is named signIn
65
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides65 Sessions …
66
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides66 Sessions … Retrieve signIn parameter value
67
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides67 Sessions … Normal processing: signIn parameter is present in HTTP request
68
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides68 Sessions … Generate HTML for response
69
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides69 Sessions Thank-you page Must escape XML special characters in user input
70
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides70 Sessions … Assign a value to the signIn session attribute
71
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides71 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
72
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides72 Sessions … Error processing (return user to sign-in form)
73
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides73 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)
74
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides74 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
75
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides75 Cookies Tomcat sends session ID as value of cookie named JSESSIONID
76
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides76 Cookies Cookie-enabled browser returns session ID as value of cookie named JSESSIONID
77
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides77 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
78
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides78 Cookies Cookies are expired by client (server can request expiration date)
79
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides79 Cookies
80
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides80 Cookies Return array of cookies contained in HTTP request
81
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides81 Cookies Search for cookie named COUNT and extract value as an int
82
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides82 Cookies
83
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides83 Cookies Send replacement cookie value to client (overwrites existing cookie)
84
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides84 Cookies Should call addCookie() before writing HTML
85
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides85 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
86
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides86 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
87
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides87 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
88
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides88 URL Rewriting Tomcat adds session ID within HTML document to all URL’s referring to the servlet Session ID = 4235
89
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides89 URL Rewriting Subsequent request will contain session ID in the URL of the request Session ID = 4235
90
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides90 URL Rewriting Next response must again add session ID to all URL’s Session ID = 4235
91
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides91 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
92
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides92 URL Rewriting HttpServletResponse method encodeURL() will add session id path parameter to argument URL Relative URL of servlet Original servlet Servlet using URL rewriting
93
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides93 URL Rewriting Must rewrite every servlet URL in every document Security issues Web site using URL rewriting User A URL with session ID 7152
94
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides94 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
95
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides95 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
96
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides96 More Servlet Methods
97
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides97 More Servlet Methods
98
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides98 More Servlet Methods
99
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides99 More Servlet Methods Response buffer All data sent to the PrintWriter object is stored in a buffer When the buffer is full, it is automatically flushed: Contents are sent to the client (preceded by header fields, if this is the first flush) Buffer becomes empty Note that all header fields must be defined before the first buffer flush
100
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides100 More Servlet Methods
101
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides101 More Servlet Methods In addition to doGet() and doPost(), servlets have methods corresponding to other HTTP request methods doHead() : automatically defined if doGet() is overridden doOptions(), doTrace() : useful default methods provided doDelete(), doPut() : override to support these methods
102
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides102 Data Storage Almost all web applications (servlets or related dynamic web server software) store and retrieve data Typical web app uses a data base management system (DBMS) Another option is to use the file system Not web technologies, so beyond our scope Some Java data storage details provided in Appendices B (file system) and C (DBMS) One common problem: concurrency
103
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides103 Concurrency
104
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides104 Concurrency Tomcat creates a separate thread for each HTTP request Java thread state saved: Which statement to be executed next The call stack: where the current method will return to, where that method will return to, etc. plus parameter values for each method The values of local variables for all methods on the call stack
105
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides105 Concurrency Some examples of values that are not saved when a thread is suspended: Values of instance variables (variables declared outside of methods) Values of class variables (variables declared as static outside of methods) Contents of files and other external resources
106
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides106 Concurrency // Output HTML document
107
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides107 Concurrency
108
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides108 Concurrency Java support thread synchronization Only one synchronized method within a class can be called at any one time Only one thread at at time can call doGet()
109
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides109 Concurrency
110
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides110 Concurrency Web application with multiple servlet classes and shared resource:
111
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides111 Concurrency Solution: create a shared class with synchronized static methods called by both servlets CounterFileCounterReaderCounterWriter readAndReset()incr() File
112
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides112 Common Gateway Interface CGI was the earliest standard technology used for dynamic server-side content CGI basics: HTTP request information is stored in environment variables (e.g., QUERY_STRING, REQUEST_METHOD, HTTP_USER_AGENT) Program is executed, output is returned in HTTP response
113
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides113 Common Gateway Interface Advantage: Program can be written in any programming language (Perl frequently used) Disadvantages: No standard for concepts such as session May be slower (programs normally run in separate processes, not server process)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.