Working in JSP

Although Java is an expansive language, when working in JSP, you'll spend much of the time interacting with just a few elements. These elements allow your JSP pages to react to form submissions, redirect page requests, and transfer data back and forth between your database and the client browser. Therefore, it's important to be familiar with the following objects:

The HTTP Response Sends information to the client

The HTTP Request Retrieves information from the client

JDBC Communicates with databases

JavaBeans Communicates with Java classes

The HTTP Response

One of three things happens when the server responds to a request from a web browser: the server redirects the request, returns data, or returns an error. Regardless of the response, there are two components, a header and the data. The HTTP header contains a great deal of information, such as the type of content, the expiration date, cookies, and so on. In this section, we'll show you how to accomplish two common tasks: write a cookie through the client's web browser and redirect the client's request to another page.

Writing a Cookie

As you know, cookies are small text files of information that your servlet can write to the client browser. Cookies are extremely useful to establish such things as where and when the user accessed your site or whether the user is a new or returning visitor. With JSP, you have detailed access to cookies and the data stored in cookies. A cookie can have a name, a value, and several optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. However, some web browsers have bugs in how they handle the optional attributes. Therefore, use optional attributes sparingly.

For a cookie to persist on the client's computer, you must write three attributes: name, value, and expiration. To see how to write such a cookie, take a look at Listing 12.7. This page, cookiewrite.jsp, writes the database ID of the site visitor to the visitor's computer and displays the cookie's value, name, and time of expiration, as shown in Figure 12.5. At a later time, you can then retrieve the visitor database ID to properly identify the visitor. As you can see, the following lines create a key and a value in the cookie. The key, userSID, is a name to set or retrieve the cookie value of 50. The next line sets the expiration date of the cookie.

Listing 12.7: COOKIEWRITE.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"     import="java.sql.*" errorPage="" %>  <%     Cookie cookie = new Cookie ("userSID", "50");    cookie.setMaxAge(365 * 24 * 60 * 60);    response.addCookie(cookie);  %> <html> <head>  <title>Cookie Write Example</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> <%=cookie.getName()%><br> <%=cookie.getValue()%><br> <%=cookie.getMaxAge()%><br> </body> </html> 
end example

click to expand
Figure 12.5: Viewing the output from cookiewrite jsp in Internet Explorer

Note 

Cookies are messages passed to a web browser from a web server. If allowed, the web browser saves these messages as text files on a user's computer. The cookie is then forwarded back to the web server with each subsequent page request the user makes to the website. Web servers and web applications primarily use cookies to identify users. However, as the developer, you can store any piece of information that fits into the three parts of a cookie—a variable name, a value, and a date or time of expiration.

Redirecting Requests

Another task you can accomplish with the HTTP response header is a server-side redirect, which sends a visitor to a completely different URL. A perfect example of a redirect is to require a username and password to protect a page. If the correct username and password are not passed to the page, the page redirects the user to a login page. We'll talk more about security in a later chapter.

Since the redirect occurs in the HTTP header, further processing of the current JSP script file stops and the visitor is sent to a different URL. Listing 12.8 demonstrates a simple redirect to the helloworld.jsp page. You can see the results in Figure 12.6.

Listing 12.8: REDIRECT.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"     import="java.sql.*" errorPage= "" %>  <% response.sendRedirect("helloworld.jsp"); %>  <html> <head> <title>Redirect Example</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> </body> </html>
end example

click to expand
Figure 12.6: The result of redirecting to the helloworld jsp page

The HTTP Request

When a web browser requests a page, it passes additional information through the HTTP header. Your JSP pages have access to all the information in that incoming request. Essentially, the HTTP header consists of a data structure of information sent by the browser to the server. All this information is accessible to you through JSP. In this section, we'll demonstrate how to access data submitted through a form and through the URL address, how to read the value of a cookie on the client's computer, and how to retrieve traditional server variables.

Accessing Form and URL Data

Unlike other web technoligies, JSP makes no distinction between form data submitted by the Get and Post methods. Therefore, both submitted form data and variables passed through the URL address are available to you through the same two functions—getParameter() and getParameterValues().

The getParameter() Function

The getParameter() function returns the first value attached to the named parameter. For example, the form in Listing 12.9 targets the JSP page in Listing 12.10. The targeted JSP page prints out the submitted form value of the passed form field "Name". Figures 12.7 and 12.8 show the browser results.

Listing 12.9: HELLOWORLD_FORM.HTM

start example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html> <head> <title>Hello World Form</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body>  <form name="HelloWorld" method="post" action="helloWorld_action.jsp">   <label>Your Name:   <input name="Name" type="text" size="25" maxlength="25"></label>   <input name="" type="submit" value="Submit">  </form> </body> </html> 
end example

Listing 12.10: : HELLOWORLD_ACTION.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"     import="java.sql.*" errorPage="" %>  <html> <head>  <title>Hello World Form Action</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> Hello World, my name is <%= request.getParameter("Name") %> </body> </html>
end example

click to expand
Figure 12.7: Viewing helloWorld_ form.htm in Internet Explorer

click to expand
Figure 12.8: Viewing the output from helloWorld_ action.jsp in Internet Explorer

The getParameterValues() Function

In cases of multiple form fields such as check boxes or text fields, you use getParameterValues() to return every value attached to the named parameter. For example, the form in Listing 12.11 targets the JSP page in Listing 12.12. The targeted JSP page places the multiple values in an array and loops through the array, printing the submitted form values of the form field "Name". Figures 12.9 and 12.10 show the browser results.

Listing 12.11: HELLOWORLD_FORM2.HTM

start example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html> <head> <title>Hello World Form 2</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body>  <form name="HelloWorld" method="post" action="helloWorld_action2.jsp">  <label>Your Name:<br>  <input name="Name" type="checkbox" size="25" maxlength="25"     value="Clark"></label>Clark<br>  <input name="Name" type="checkbox" size="25" maxlength="25"     value="Lois">Lois<br>  <input name="Name" type="checkbox" size="25" maxlength="25"     value="Jimmy">Jimmy<br>   <input name="" type="submit" value="Submit">  </form> </body> </html>
end example

Listing 12.12: HELLOWORLD_ACTION2.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"     import="java.sql.*" errorPage="" %>  <html> <head>  <title>Hello World Form Action 2</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> Hello World, my name is: <br>  <% String names[] = request.getParameterValues("Name");  for (int i = 0; i < names.length; i++) { %>  <%= names[i] %><br> <% } %> </body> </html>
end example

click to expand
Figure 12.9: Viewing helloWorld_ form2.htm in Internet Explorer

click to expand
Figure 12.10: Viewing the output from helloWorld_ action2.jsp in Internet Explorer

Accessing Cookies

To read a cookie in JSP, you first read all the URL-attached cookies from the request HTTP header. You then loop through the cookies to find a specific cookie name and value. For example, Listing 12.13 loops through the cookies contained in the request HTTP header—looking for a cookie named

Listing 12.13: COOKIEREAD.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"      import="java.sql.*" errorPage="" %>  <% Cookie nameCookie = null; String cookieName = "userSID";  String cookieValue = ""; Cookie[] cookies = request.getCookies(); for (int i=0; i < cookies.length; i++) {     nameCookie = cookies[i];     if (nameCookie.getName().equals(cookieName)) {     cookieName = nameCookie.getName();        cookieValue = nameCookie.getValue();     } } %>  <html>  <head>  <title>Cookie Read</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> Your userSID is <%= cookieValue %>  </body> </html> 
end example

userSID. When it finds the userSID cookie, the JSP page reads its value to find the database ID of the returning visitor (which our web application had previously written in a cookie). Figure 12.11 shows the results in a web browser.

click to expand
Figure 12.11: Viewing the results of cookieread jsp in a browser

Server Variables

If you are familiar with other web technologies, you are probably familiar with server variables— collections of information derived from the HTTP header information and sometimes from the web server. For example, you can discern the virtual path of the executing script page from the server variable request.getServletPath(). Although you won't be using server variables every day, they are a core resource you should be familiar with while you develop JSP web applications. Table 12.3 shows the most common server variables available to JSP, and Listing 12.14 shows the server variables used in a JSP page.

Table 12.3: SERVER VARIABLES

Variable

Description

request.getAuthType()

If the web server supports user authentication, this is the authentication method.

request.getContentLength()

The length of the CONTENT_TYPE.

request.getContentType()

For requests with attached information, such as a HTTP POST and PUT, this is the data content type.

request.getPathInfo()

The path information of the request. For example, relative paths, such as pdfs/mypdf.asp, can access request pages. The extra information in the path information is sent as PATH_INFO.

request.getPathTranslated()

The translated version of PATH_INFO with virtual-to-physical mapping. In the PATH_INFO example, the PATH_TRANSLATED value may be C:\inetpub\wwwroot\test\pdfs\ mypdf.pdf.

request.getQueryString()

Any information that follows the question mark (?) in the URL of the current page.

request.getRemoteAddr()

The IP address of the remote host making the request.

request.getRemoteHost()

The hostname making the request.

request.getRemoteUser()

If the server supports user authentication this is the authenticated username.

request.getMethod()

The form submission method of the request.

request.getServletPath()

The virtual path to the script being executed.

request.getServerName()

The server's hostname, DNS alias, or IP address.

request.getServerPort()

The port number of the request.

request.getProtocol()

The name and revision of the information protocol.

Listing 12.14: SERVERVARIABLES.JSP

start example
<%@ page contentType="text/html; charset=iso-8859-1" language="java"     import="java.sql.*" errorPage="" %>   <html> <head>  <title>Server Variables</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> request.getAuthType(): <%= request.getAuthType() %><br>  request.getContentLength(): <%= request.getContentLength() %><br>  request.getContentType(): <%= request.getContentType() %><br>  request.getHeader("Xxx-Yyy"): <%= request.getHeader("Xxx-Yyy") %><br>  request.getPathInfo(): <%= request.getPathInfo() %><br>  request.getPathTranslated(): <%= request.getPathTranslated() %><br>  request.getQueryString(): <%= request.getQueryString() %><br>  request.getRemoteAddr(): <%= request.getRemoteAddr() %><br>  request.getRemoteHost(): <%= request.getRemoteHost() %><br>  request.getRemoteUser(): <%= request.getRemoteUser() %><br>  request.getMethod(): <%= request.getMethod() %><br>  request.getServletPath(): <%= request.getServletPath() %><br>  request.getServerName(): <%= request.getServerName() %><br>  request.getServerPort(): <%= request.getServerPort() %><br>  request.getProtocol(): <%= request.getProtocol() %> </body> </html>
end example

JDBC: Connecting to a Database

We've reviewed the more common aspects of the JSP language; however, any sophisticated website requires a database. To enable your JSP pages to communicate with a database, you use a JDBC connection. With a JDBC connection to a database, you can pull and push data from your JSP web application. Luckily, Dreamweaver MX gives you the choice of seven JDBC connection options right out of the box:

  • Custom JDBC Connections

  • IBM DB 2 App Driver (DB2)

  • IBM DB 2 Net Driver (DB2)

  • MySQL Driver (MySQL)

  • Oracle Thin Driver (Oracle)

  • Inet Driver (SQL Server)

  • Sun JDBC-ODBC Driver (ODBC Database)

As you can see from the list, many of the connection options, such as the Oracle Thin Driver, allow your JSP web application to connect natively (directly) to the database. This typically increases response time and can speed up your application. However, to use the native database connection drivers, you need a bit of technical information about your database and the server it resides on, plus you need to be somewhat knowledgable about the connection driver (version, eccentriciities, that sort of thing). If you do not know or do not want to deal with this additional information, we suggest the good old JDBC-ODBC Driver. With JDBC-ODBC, the only information you need is the name of the ODBC connection to the database server. For example, to connect to our sample Books database, we know our database administrator has created a connection on the web server called "bookTrackerPublic". So, to establish a connection to our database in Dreamweaver MX, we open the Sun JDBC-ODBC Driver (ODBC Database) dialog box, as shown in Figure 12.12. Next, we enter a name for our connection and replace [odbc dsn] with our ODBC connection name. All that's left to do is close the dialog box and begin pulling data. Simple as can be.

click to expand
Figure 12.12: The Dreamweaver MX Sun JDBCODBC Driver (ODBC Database) dialog box

JavaBeans: Communicating with Java Classes

Up to now, you've seen how you can incorporate Java code directly into your web pages. Those JSP web pages are compiled into servlets and respond to web page requests to quickly build dynamic web pages. This model of compiling JSP script pages is powerful and fast. However, as you can imagine, the more complex the code, the longer it takes to compile a JSP script page into a servlet. JavaBeans to the rescue. JavaBeans allow you to permanently compile complex Java code and access the compiled JavaBean through a JSP script page.

A JavaBean is actually a complied Java class—a bit of software you can execute from your JSP script pages. Essentially, a JavaBean must follow only two rules:

  1. You must be able to communicate with a JavaBean.

  2. You must be able to create an instance of a JavaBean without passing it any dependent values.

How do you know when and what code you should move from a JSP script page to a JavaBean? It's helpful to think of your web application from a functional perspective. If you can recognize code that is used over and over again through your web application, it might make sense to extract the code into a Java class and compile it into a JavaBean. You then simply access the compiled JavaBean from all your JSP script pages.

Dreamweaver MX deals with JavaBeans in a way that is similar to the way it deals with other sources of data such as a database. JavaBeans even appear in the Bindings panel, allowing you to expand a JavaBean to view its properties. You can also drag and drop the properties onto your JSP script page. Of course, to access a JavaBean in this way, Dreamweaver MX must have complete access to the Bean class. Therefore, a copy of the Bean class must be in the Configuration/classesfolder under the main Dreamweaver MX application folder. However, if you are developing with Dreamweaver MX on your web server, it is acceptable to have the Bean class in the normal system classpath.

Dreamweaver MX makes it simple to access a JavaBean through a JSP page. You can choose to define a JavaBean or a JavaBean collection in the Bindings panel, or you can click the Use JavaBean button on the JSP toolbar. To define a JavaBean or a JavaBean collection in the Bindings panel, follow these steps:

  1. Activate the Bindings panel.

  2. Choose Panel ® JavaBean or Panel ® JavaBean Collection.

  3. In the resulting dialog box, configure the JavaBean or JavaBean collection.

In the example in Figure 12.13, we've chosen the TestCollection.MusicCollection Macromedia sample JavaBean. Typically, if Dreamweaver MX can find your Bean class, Dreamweaver will display it as a class choice.

click to expand
Figure 12.13: The JavaBean Collection dialog box

After you configure the JavaBean or JavaBean collection, you'll see the properties in the Bindings panel as shown in Figure 12.14.

click to expand
Figure 12.14: The Bindings panel

To use a JavaBean in your JSP page, simply click the Use JavaBean button to open the UseBean dialog box, as shown in Figure 12.15, and enter the information requested. You can instantiate a JavaBean using nothing more than the ID and Scope attributes.


Figure 12.15: The Dreamweaver MX UseBean dialog box

After you create an instance of the JavaBean in your JSP script page, you can interact with the JavaBean by setting JavaBean properties or getting JavaBean properties. To set or get a JavaBean property, use the GetProperty and SetProperty commands. Both of these commands are also available on the Dreamweaver MX JSP toolbar and in the Bindings panel. GetProperty gets the value of a bean property so you can display it in a result page. SetProperty sets a bean property value. Figures 12.16 and 12.17 show the SetProperty and GetProperty dialog boxes. Alternatively, if you registered your JavaBean or JavaBean collection in the Bindings panel of Dreamweaver MX, you can simply drag and drop your JavaBean properties into your JSP script page.


Figure 12.16: The Dreamweaver MX SetProperty dialog box


Figure 12.17: The Dreamweaver MX GetProperty dialog box

start sidebar
For Further Information

You'll have no trouble finding information about Java and JSP, but we wanted to list a few of our favorite sites. The primary site, of course, is that of the creator of Java, Sun Microsystems. At http://java.sun.com/products/jsp/, you can find information about Java, JSP, and Sun's own JSP web server. Speaking of web servers, Macromedia's JRun (www.macromedia.com/software/jrun/) is one of the most stable and easy to administrate available. Plus Macromedia keeps extensive content online for JRun JSP devotees. In addition to the corporate sites, don't forget the information portal sites such as the JSP Resource Index (www.jspin.com/) and the newsgroups at Google (http://groups.google.com/ groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&group=comp.lang.java). Finally, check out these JSP and Java books by Sybex: Enterprise Java 2, J2EE 1.4 Complete, Mastering JSP, Mastering Java 2, J2SE 1.4, and Java Developer's Guide to E-Commerce with XML and JSP.

end sidebar



Mastering Dreamweaver MX Databases
Mastering Dreamweaver MX Databases
ISBN: 078214148X
EAN: 2147483647
Year: 2002
Pages: 214

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