Object-Oriented Enterprise Application Development Advanced Servlets.

66
Object-Oriented Enterprise Application Development Advanced Servlets
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    235
  • download

    2

Transcript of Object-Oriented Enterprise Application Development Advanced Servlets.

Object-Oriented Enterprise Application Development

Advanced Servlets

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."

Web Applications

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

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.

HTTP Requests

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.

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("<HTML><HEAD>");

Sample Code – Header(2 of 2)10. out.println("<TITLE>Header</TITLE>");11. out.println("</HEAD><BODY>");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("</BODY></HTML>");19. out.close();20. }21. }

Sample Code - OutputUser-Agent Mozilla/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

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.

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.

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();

Sample Code – Parameter(2 of 2)9. out.println("<HTML><HEAD>");10. out.println("<TITLE>Parms</TITLE>");11. out.println("</HEAD><BODY>");12. String firstName =

rqst.getParameter("firstname");13. String lastName =

rqst.getParameter("lastname");14. out.println( firstName + ", " +

lastName );15. out.println("</BODY></HTML>");16. out.close();17. }18. }

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

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.

Sample Code – Parameters1. <HTML><HEAD>2. <TITLE>Request Parameters Example</TITLE>3. </HEAD><BODY BGCOLOR="white"><P>4. <FORM ACTION="parms" METHOD=GET>5. First Name:6. <INPUT TYPE=TEXT SIZE=20 NAME=firstName>7. <BR>8. Last Name:9. <INPUT TYPE=TEXT SIZE=20 NAME=lastName>10. <BR>11. <INPUT TYPE=SUBMIT>12. </FORM>13. </P></BODY></HTML>

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.

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.

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.

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=flintstone

The information appears in the address bar because you used the GET method to submit the form.

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.

Sample Code – Parameters (rev.)1. <HTML><HEAD>2. <TITLE>Request Parameters Example</TITLE>3. </HEAD><BODY BGCOLOR="white"><P>4. <FORM ACTION="parms" METHOD=POST>5. First Name:6. <INPUT TYPE=TEXT SIZE=20 NAME=firstName>7. <BR>8. Last Name:9. <INPUT TYPE=TEXT SIZE=20 NAME=lastName>10. <BR>11. <INPUT TYPE=SUBMIT>12. </FORM>13. </P></BODY></HTML>

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<method>() isn't defined in the target servlet, you will receive the following message from the web server:

HTTP 404 – POST Method Not Supported

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();

Sample Code – Parameter (rev.)(2 of 3)9. out.println("<HTML><HEAD>");10. out.println("<TITLE>Parms</TITLE>");11. out.println("</HEAD><BODY>");12. String firstName =

rqst.getParameter("firstname");13. String lastName =

rqst.getParameter("lastname");14. out.println( firstName + ", " +

lastName );15. out.println("</BODY></HTML>");16. out.close();17. }

Sample Code – Parameter (rev.)(3 of 3)18. public void

doPost(HttpServletRequest rqst, HttpServletResponse resp) throws IOException, ServletException {

19. doGet(rqst, resp);20. }21. }

Servlets & State

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.

Maintaining State

There are three (3) typical methods for persisting client data across client requests:

Cookies

Databases

Sessions

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.

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.

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

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.

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.

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 SessionSampleextends HttpServlet {

6. public void doGet(HttpServletRequest rqst, HttpServletResponse resp)

7. throws ServletException, IOException {8. resp.setContentType("text/html");9. PrintWriter out = resp.getWriter();

Sample Code – Session(2 of 4)10. out.println("<html>");11. out.println("<head>");12. out.println("<title>Session</title>");13. out.println("</head>");14. out.println("<body>");15. HttpSession session =

rqst.getSession(true);16. out.println("Session ID: " +

session.getId());17. out.println("<br>");18. out.println("Created On: " +

session.getCreationTime());19. out.println("<br>");

Sample Code – Session(3 of 4)20. out.println("<br>");21. out.println("Last Accessed On: " +

session.getLastAccessedTime());22. out.println("<br>");23. String name =

rqst.getParameter("name");24. String value =

rqst.getParameter("value");25. session.setAttribute(name, value);26. out.println("<P>");27. out.println("Session Data");28. out.println("<br>");

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 + "<br>");34. }35. out.println("</body>");36. out.println("</html>");37. }

Creating Sessions(1 of 2)

To create a session, use the getSession() method on the HttpServletRequest object:

public HttpSession getSession()

public HttpSession getSession(boolean)

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.

Storing Values in Session(1 of 2)

To store a value into a session object, use the following methods:

public voidputValue(String name, Object value)

public voidsetAttribute(String name, Object value)

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.

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)

Other Session Methods

There are other useful session methods:public void removeAttribute(String name)

public boolean isNew()

Public void invalidate()

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.

Session Timeout Methods

The following methods can be used to manipulate the session timeout value:

public voidsetMaxInactiveInterval(int secs)

public int getMaxInactiveInterval()

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.

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.

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.

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()

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.

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."

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.

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.

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.

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.

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.

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 Dispatcherextends HttpServlet {

6. private void chain(HttpServletRequest rqst, HttpServletResponse resp, String URL)

7. throws ServletException, IOException {

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. }

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. else18. chain(rqst, resp, "url2");19. }20. }

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.

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.

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.

Resources

Developing Java ServletsJames Goodwill, Sam's Publishing, 1999.ISBN: 0-672-31600-5

Core Servlets and JavaServer PagesMarty Hall, Prentice-Hall, Inc., 2000.ISBN: 0-13-089340-4

Java 2 Platform, Enterprise EditionB. Shannon, et al., Addison-Wesley, 2000.ISBN: 0-201-70456-0

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.