Directives


JSP Variables

The out variable isn't the only variable available to the developer. Table 3.2 shows all of the variables the Resin server provides to the JSP page.

Table 3.2: JSP Variables

NAME

DESCRIPTION

JAVA CLASS

application

Specifies the current application

javax.servlet.ServletContext

exception

For error pages, indicates the exception thrown from the broken page

java.lang.Throwable

out

Contains the buffered stream to the HTTP response

javax.servlet.jsp.JspWriter

pageContext

Indicates the state of the current page

javax.servlet.jsp.PageContext

request

Contains the request object

javax.servlet.http. HttpServletRequest

response

Contains the response object

javax.servlet.HttpServletResponse

session

Specifies the current session

javax.servlet.HttpSession

Using the Request Variable

One of the more powerful and useful variables provided by Resin is the request variable. Every time a browser makes a file request of the server, a request variable is created. This variable includes information such as the file being requested and the header for the request, as well as any user-entered values for an HTML form. Before we look at getting values from a form, consider the following example:

 <HTML> <BODY> Request Information<BR> Your IP is <%= request.getRemoteHost() %><BR> The HTTP request was <%= request.getMethod() %><BR> The URL requested was <%= request.getRequestURI() %><BR> </BODY> <HTML> 

In this simple example, we use the Request object to obtain some generic information about the user making the request against the server. Of particular importance is the getRemoteHost() method. Unless you have made some extraordinary efforts, the administrator of the server you have accessed will have a record of the IP address from which you are browsing. This basic information is helpful, but the Request object also helps when using forms.

All of the requests to a URL contain numerous headers to hold information about the browser, user, and machine making the request. You can use the Request object to obtain the header both as a whole or individually. Consider the following code:

 <HTML> <BODY> <table border='1' > <tr><td>Header</td><td>Value</td></tr> <% Enumeration e; e = request.getHeaderNames(); while (e.hasMoreElements()} {     String key = (String)e.nextElement();     String value = request.getHeader(key);     out.println("<tr><td>");     out.println(key);     out.println("</td><td>");     out.println(value);     out.println("</td></tr>"); } %> <table> </BODY> </HTML> 

This code puts all of the header names from the Request object using the method getHeaderNames() and places them in an Enumeration object. The names are cycled through using a loop and their values extracted using the getHeader(String key) method. Both the header name and values are displayed in a table, as shown in Figure 3.3.

click to expand
Figure 3.3: Header names and values from the Request object.

If you need to look at a specific header, use code like the following:

 <% Enumeration e; e = request.getHeaderNames(); String userAgent = null; while (e.hasMoreElements()) {    String key = (String)e.nextElement();    if (key.equals("user-agent"))    {        userAgent = request.getHeader(key);        break;    } } %> <html> <body> USER-AGENT is <%= userAgent %> </body> </html> 

JSP and Forms

An HTML form is used to obtain information about users and their possible intentions at a Web site. A typical form looks like this one, found in a page called name.html:

 <HTML> <BODY> Please enter your Name: <form method='post' action='name.jsp'> <input type='text' name='username' size='35'><BR> <input type='submit'> </form> </BODY> <HTML> 

Note two important things about our form. First, notice the page set in the action directive. We are letting the system know that when the user clicks Submit, the server should make a request of the name.jsp page. This is significant because, as we just learned, a Request object is created and the object includes all the information entered in the form. The second important part of our form is the name directive in the input for the username. The name is passed along with the information entered by the user.

Now let's see what name.jsp looks like:

 <%   String name = request.getParameter( "username" );   String ip = request.getRemoteHost(); %> <HTML> <BODY> Hey, <%= name %>, thanks for providing your IP address : <%= ip %><BR> To continue to the next page, click <A HREF="address.jsp">here</A> </BODY> </HTML> 

The Request object has a built-in container for the key/value pairs from the form. You can access the container in several ways, but the easiest is to use the getParameter(String key) method. This method requires that you provide the name of the field from the form and the method will return the value entered by the user. In our example, the value is assigned to a local variable and subsequently used to address the user directly.

Using the Response Variable

When an HTML response page is created by Resin, a Response object is attached with information about the page. The information includes numerous headers, date and timestamps, and possibly cookies. From the application's perspective, there are other uses for the Response object. Let's look at two of them: redirection and encoding.

Response Redirection

In most situations, a JSP page will handle some function needed by the user and return an appropriate page to the browser. The user works with the new page and is subsequently sent to another JSP page. At times, though, a JSP page will be processing information from the user and instead of that page being able to process the user's information, the system has to direct processing to another page. This redirection is accomplished using the Response object and the sendRedirect() method. For example, consider the following code based on the name.jsp page shown earlier:

 <%   String name = request.getParameter( "username" );   String ip = request.getRemoteHost();   if (ip.equals("192.168.1.1"))     response.sendRedirect("noip.jsp") %> <HTML> <BODY> Hey, <%= name %>, thanks for providing your IP address : <%= ip %><BR> To continue to the next page, click <A HREF="address.jsp">here</A> </BODY> </HTML> 

In this code, the IP address of the requesting host is compared against the IP 192.168.1.1. If the IP matches, the user is directed to a page called noip.jsp where the user will be handled appropriately.

Response Encoding

When sites have to keep track of information about users, they will commonly use cookies. These small objects are stored on the hard drive of the remote machine. However, cookies can be turned off by the user; in this case, you must use a session ID. The session ID is attached to all of the URLs in the system. The session ID is attached to a URL using the Response object and the session ID is obtained using the Request object. In most cases, the system starts to attach the session ID to pages once a user logs. Consider this page, called authenticate.jsp:

 <%   String username = request.getParameter( "username" );   String password = request.getParameter( "password" );   if (check(username, password)) {     String newURL = response.encodeURL("store.jsp");     response.sendRedirect(newURL);   } else {     response.sendRedirect("login.jsp");   } %> 

A user reaches this page after entering his or her username and password from a login page. If the username and password are valid, the code encodes the link store.jsp with the session ID of the Session object, which has been automatically created for the current user of the site. Once the URL has been encoded with the session ID, the sendRedirect() method is used to present the store.jsp page to the user. If the username/password combination isn't valid, the user is directed to the login.jsp page to try again.

Once the session ID has been attached to the URL, all links must use the session ID in order to maintain the Session object associated with the user. If the user goes to another page without the session ID, the session is lost.

Using the Application Variable

Another object associated with all JSP pages is the Application object. This object is global in scope and shared among all users of the JSP application.

The object has a container associated with it where objects can be stored for a time and utilized through the application. Objects are assigned to the Application object using the setAttribute(String, Object) method. For example:

 <%   java.util.Date date = new java.util.Date();   application.setAttribute("today", date); %> 

This code could be executed by any page in the site. Likewise, any page could access the information in the object with code like the following:

 <%   java.util.Date date = (java.util.Date)application.getAttribute("today"); %> 

Using the Session Variable

In our code, we touched on the idea of sessions for the users who access our site. When a new user hits our site, the system automatically creates a new Session object for the user. The Session object is like the Application object in that it includes a container to hold information as well as other methods for session information. When the URL is encoded or cookies used, the system makes sure that the same session variable is associated with the same user at every page.

Since the Session object is kept unique per user, we can use it to store information like shopping carts or personal information. For example, we might expand our code from earlier to keep track of the user's name:

 <%   String username = request.getParameter( "username" );   String password = request.getParameter( "password" );   if (check(username, password)) {     session.setAttribute("username", username);     String newURL = response.encodeURL("store.jsp");     response.sendRedirect(newURL);   } else {     response.sendRedirect("login.jsp");   } %> 

When the user is redirected to the store.jsp page, we can extract the user-name and provide a more personalized visit for our customer:

 <HTML> <BODY> Hello, <%= session.getAttribute( "username" ) %> </BODY> </HTML> 




Mastering Resin
Mastering Resin
ISBN: 0471431036
EAN: 2147483647
Year: 2002
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net