Download presentation
Presentation is loading. Please wait.
1
Object-Oriented Enterprise Application Development Advanced Servlets
2
Topics During this class we will examine: Sending data from an HTTP client to a servlet. Responding to an HTTP request. Providing the user with a "shopping cart."
3
Web Applications
4
Web Pages (1 of 2) In the modern inter- and intranet worlds, web pages have replaced the old GUI client. Web pages have many advantages over traditional GUI clients: Easier to distribute Easier to maintain Globally available Smaller footprint
5
Web Pages (2 of 2) For Java servlets to be a true alternative to competing technologies, they must be able to process data from web pages. To manipulate such data, we use the HttpServletRequest object that is passed to the servlet's service() method.
6
HTTP Requests
7
Headers The first thing to look at is the content of a browser's request header. The request header provides high-level information about the client that issued the original request. This kind of information is invaluable when writing an application that must be compatible across multiple browsers.
8
Sample Code – Header (1 of 2) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Header extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter(); 9. out.println(" ");
9
Sample Code – Header (2 of 2) 10. out.println(" Header "); 11. out.println(" "); 12. Enumeration enum = rqst.getHeaderNames(); 13. while ( enum.hasMoreElements() ) { 14. String name = (String)enum.nextElement(); 15. String value = rqst.getHeader(name); 16. out.println( name + "=" + value ); 17. } 18. out.println(" "); 19. out.close(); 20. } 21.}
10
Sample Code - Output User-AgentMozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0) Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, application/x-comet, */* Host localhost:8080 Accept-Encoding gzip, deflate Accept-Language en-us Referer http://localhost:8080/examples/servlets/index.html Connection Keep-Alive
11
Name-Value Pairs All data is passed to a servlet as a set of name-value pairs. This approach simplifies the process of passing arguments. This is the same technique used to read initialization parameters from the web.xml file.
12
Parameters While the request header provides valuable information to the servlet, it doesn't contain the actual data submitted by a web-based form. This data is provided as a set of parameters within the HttpServletRequest. The next code sample illustrates how to access these values.
13
Sample Code – Parameter (1 of 2) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Parameter extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter();
14
Sample Code – Parameter (2 of 2) 9. out.println(" "); 10. out.println(" Parms "); 11. out.println(" "); 12. String firstName = rqst.getParameter("firstname"); 13. String lastName = rqst.getParameter("lastname"); 14. out.println( firstName + ", " + lastName ); 15. out.println(" "); 16. out.close(); 17. } 18.}
15
Passing Parameters Now that we've seen how to access the parameters within our servlet, we need to see how to pass them to the original request. We'll look at two techniques: HTML form tags Direct encoding on the URL
16
Web Pages The most common way of passing data to a servlet is through a web-based form on an HTML page. This allows us to hide the data from the user. The GET or POST methods change how the data is passed to the servlet.
17
Sample Code – Parameters 1. 2. Request Parameters Example 3. 4. 5.First Name: 6. 7. 8.Last Name: 9. 10. 11. 12. 13.
18
Form Tags The FORM tag identifies a set of fields that will be submitted to the servlet as a group. The ACTION identifies the path of the servlet to be executed when the FORM is submitted. The METHOD identifies whether the FORM is submitted using the GET or POST method.
19
Form Fields (1 of 2) The FORM tag identifies a kind of container to the browser, but it's the individual fields that provide the actual data to the servlet. Each INPUT tag identifies a data source. The NAME of the input is the argument to the getParameter() method. Data is only submitted to the servlet when the form is submitted.
20
Form Fields (2 of 2) Every form field in a form will be submitted whether or not a value has been provided. If a field has been submitted and it has no value, the getParameter() method will return an empty string. It's the developer's task to perform all necessary typecasts.
21
GET vs. POST Methods (1 of 3) When the HTML form in the prior example is submitted, you'll see the browser's address bar change to: http://localhost:8080/se452/parms ?firstname=fred&lastname=flintst one The information appears in the address bar because you used the GET method to submit the form.
22
GET vs. POST Methods (2 of 3) There are times we don't want this information displayed in the address bar for security or privacy reasons. To avoid displaying the data in the address bar, change the form to submit using the POST method.
23
Sample Code – Parameters (rev.) 1. 2. Request Parameters Example 3. 4. 5.First Name: 6. 7. 8.Last Name: 9. 10. 11. 12. 13.
24
GET vs. POST Methods (3 of 3) If you attempt to submit a form using GET or POST (or any other HTTP method) and the corresponding do () isn't defined in the target servlet, you will receive the following message from the web server: HTTP 404 – POST Method Not Supported
25
Sample Code – Parameter (rev.) (1 of 3) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Parameter extends HttpServlet { 6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 7. resp.setContentType("text/html"); 8. PrintWriter out = resp.getWriter();
26
Sample Code – Parameter (rev.) (2 of 3) 9. out.println(" "); 10. out.println(" Parms "); 11. out.println(" "); 12. String firstName = rqst.getParameter("firstname"); 13. String lastName = rqst.getParameter("lastname"); 14. out.println( firstName + ", " + lastName ); 15. out.println(" "); 16. out.close(); 17. }
27
Sample Code – Parameter (rev.) (3 of 3) 18. public void doPost(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException { 19. doGet(rqst, resp); 20. } 21.}
28
Servlets & State
29
Stateless Connections Just to keep things lively, most browser's have a stateless relationship to the web server. This means that once a browser closes its connection to the server, the server loses all knowledge of the client. Each request generated by the client results in a new connection to the server.
30
Maintaining State There are three (3) typical methods for persisting client data across client requests: Cookies Databases Sessions
31
Cookies (1 of 2) Cookies are small amounts of data that can be written to the client machine. They are actually a name-value pair. When the browser issues a request to a server, all cookies created by that server will be sent along with the request. This technique raises significant issues: Cookies could be disabled within the client.
32
Cookies (2 of 2) Cookies have specific limitations: There can only be 20 cookies from a given server saved to a user's disk. Each cookie can only be a maximum of 4K for both the name and value combined.
33
Database We could store all client state data into a database of some sort. This isn't uncommon, but there are still issues: Volume Persistence
34
Sessions (1 of 2) The servlet specification provides for a class called an HttpSession. It is maintained on the application server and is used to hold whatever data the application chooses to place within it. This allows our application to provide the standard "shopping cart" metaphor.
35
Sessions (2 of 2) Each session has its own internal identifier called a session id. This value is created by the server and associated with the session when it is created on behalf of a client. Sessions must be created by the application; they are not provided to a client by default.
36
Sample Code – Session (1 of 4) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class SessionSample extends HttpServlet { 6.public void doGet(HttpServletRequest rqst, HttpServletResponse resp) 7.throws ServletException, IOException { 8. resp.setContentType("text/html"); 9. PrintWriter out = resp.getWriter();
37
Sample Code – Session (2 of 4) 10. out.println(" "); 11. out.println(" "); 12. out.println(" Session "); 13. out.println(" "); 14. out.println(" "); 15. HttpSession session = rqst.getSession(true); 16. out.println("Session ID: " + session.getId()); 17. out.println(" "); 18. out.println("Created On: " + session.getCreationTime()); 19. out.println(" ");
38
Sample Code – Session (3 of 4) 20. out.println(" "); 21. out.println("Last Accessed On: " + session.getLastAccessedTime()); 22. out.println(" "); 23. String name = rqst.getParameter("name"); 24. String value = rqst.getParameter("value"); 25. session.setAttribute(name, value); 26. out.println(" "); 27. out.println("Session Data"); 28. out.println(" ");
39
Sample Code – Session (4 of 4) 29. Enumeration names = session.getAttributeNames(); 30. while (names.hasMoreElements()) { 31. String n = (String)names.nextElement(); 32. Object v = session.getAttribute(name); 33. out.println(n + " = " + v + " "); 34. } 35. out.println(" "); 36. out.println(" "); 37.}
40
Creating Sessions (1 of 2) To create a session, use the getSession() method on the HttpServletRequest object: public HttpSession getSession() public HttpSession getSession(boolean)
41
Creating Sessions (2 of 2) We usually want to control when a session is created. It's common practice to include session creation as part of a successful user login. We can check for an existing session when a user attempts to access a page. If the session doesn't exist, we can automatically send the user to a login page.
42
Storing Values in Session (1 of 2) To store a value into a session object, use the following methods: public void putValue(String name, Object value) public void setAttribute(String name, Object value)
43
Storing Values in Session (2 of 2) Any data can be stored within the session. The only requirement is that the data be serializable. Serializability is a requirement for most implementations of session distribution.
44
Recalling Values from Session To recall a value from a session object, use the following methods: public Object getValue(String name) public Object getAttribute(String name)
45
Other Session Methods There are other useful session methods: public void removeAttribute(String name) public boolean isNew() Public void invalidate()
46
Session Timeout It is common to specify an application-wide session timeout. As sessions are created an used, they absorb resources such as disk and possible bandwidth. The application has no way of knowing when or even if a user will issue another request that uses the session.
47
Session Timeout Methods The following methods can be used to manipulate the session timeout value: public void setMaxInactiveInterval(int secs) public int getMaxInactiveInterval()
48
Session ID (1 of 3) Each session has its own unique identifier. This ID is generated by the application server and cannot be changed using the API. Somehow the server must make the client aware of this ID so that it can be re- submitted on later requests.
49
Session ID (2 of 3) There are three (3) techniques used to communicate the session ID to the client: Cookies URL Rewriting Hidden Form Fields All of these approaches are transparent to the client and the developer.
50
Session ID (3 of 3) We typically choose two (2) or more of these techniques when storing a session ID. This allows for variations in browser and client configuration and capabilities.
51
Retrieving the Session ID Sometimes we might want to access the ID of the session. We may want to store the ID within a database. We can access this ID using the following method on the HttpSession object: public String getId()
52
Session Distribution To make our application's fault tolerant, many production-grade application servers support session distribution. This means that a user's session is propagated to multiple machines. If the primary machine fails, the user's session is available on the secondary machine.
53
Namespaces (1 of 2) The names that we give to our session variables are arbitrary. There is a strong possibility that two (2) or more developers on a project will choose identical names for their session values. To avoid this problem, I recommend the use of session "namespaces."
54
Namespaces (2 of 2) As with namespaces in programming languages, the idea is to ensure that each session variable has a truly unique name. There are several ways of doing this. One approach is to prefix each session variable with the name of the servlet that is responsible for creating it.
55
Session Wrappers At one client we created a session wrapper class. Its job was to provide a consistent naming scheme for all session names. The name included a "scope" such as global data vs. servlet-specific data. This allowed us to fully qualify any session variable.
56
Servlet Roles Servlets are typically used as controllers. A request is received from a client, often a web page. The servlet interrogates the request and dispatches to some business entity, often an EJB, to perform some additional processing. At some point a response is sent back to the client, often the result of a JSP.
57
Separating Business & Presentation Logic To achieve the separation of business logic from presentation, we need the ability to integrate servlets with other J2EE components. This allows us to solve problems that involve a single servlet displaying returning different responses based on the request that was issued.
58
Request Dispatcher For a servlet to branch, or chain, to another servlet or JSP, it must first get access to a RequestDispatcher object. This object is used to transfer control to the specified URL. This allows us to programmatically choose the next response that will be presented to the client.
59
Sample Code – Dispatcher (1 of 3) 1.import java.io.*; 2.import java.util.*; 3.import javax.servlet.*; 4.import javax.servlet.http.*; 5.public class Dispatcher extends HttpServlet { 6. private void chain(HttpServletRequest rqst, HttpServletResponse resp, String URL) 7. throws ServletException, IOException {
60
Sample Code – Dispatcher (2 of 3) 8. RequestDispatcher dispatcher = getServletContext(). getRequestDispatcher(URL); 9. dispatcher.forward(rqst, resp); 10. } 11. public void doPost(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException { 12. doGet(rqst, resp); 13. }
61
Sample Code – Dispatcher (3 of 3) 14. public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException { 15. if (rqst.getParameter("uid") == null) 16. chain(rqst, resp, "url1"); 17. else 18. chain(rqst, resp, "url2"); 19. } 20.}
62
Forward When forward() method of a RequestDispatcher is invoked, the servlet effectively gives up its right to issue any part of the response back to the client. An attempt to use the PrintWriter on the response either before or after a call to forward() will result in an error.
63
Include If the servlet does need to write data back to the response prior to chaining to another servlet or JSP, then we must use the include() method of the RequestDispatcher class. This method behaves just as the forward() method does save that there are no restrictions on the use of the output stream.
64
Review During this class we have discussed: Sending data from a web form to a servlet. Processing the parameters of an HTTP request. Providing the user with a "shopping cart." Discussed the HttpSession class. Described techniques useful for dealing with a session object.
65
Resources Developing Java Servlets James Goodwill, Sam's Publishing, 1999. ISBN: 0-672-31600-5 Core Servlets and JavaServer Pages Marty Hall, Prentice-Hall, Inc., 2000. ISBN: 0-13-089340-4 Java 2 Platform, Enterprise Edition B. Shannon, et al., Addison-Wesley, 2000. ISBN: 0-201-70456-0
66
Coming Attractions Next week we'll begin separating the presentation logic from the business logic using JavaServer Pages. Please read Chapters 10 & 11 in your text.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.