Exercises
Exercises
Do items 1-4 in order, then try whichever of the remaining exercises grab your interest and you have time for. See C:\Servlets+JSP\Exercise-Solutions\lecture1 for solutions.
1. 2.
Open the C:\Servlets+JSP\ directory and double-click the icon to start Tomcat. Verify that the server is running by opening http://localhost/ in your browser. Open http://archive.coreservlets.com in your browser (or use your local copy if you have one), then right-click on HelloWorld.java (Chapter 2) to download it to the C:\Servlets+JSP directory. Compile it using javac HelloWorld.java (DOS Window) or with javac %f (from the UltraEdit Advanced/DOS Command menu), and copy the .class file to tomcat_install_dir\webapps\ROOT\WEB-INF\classes (there should be a shortcut in C:\Servlets+JSP to make this task easier). Then, check that the servlet is working by using the URL http://localhost/servlet/HelloWorld. Download HelloWWW.java into the C:\Servlets+JSP directory, edit it so that it outputs Hello YourName, compile it, and copy the .class file to the shortcut to .../WEB-INF/classes. Execute the servlet with http://localhost/servlet/HelloWWW. Create a coreservlets directory within C:\Servlets+JSP. Open http://archive.coreservlets.com in your browser (or use your local copy if you have one), then right-click on ServletUtilities.java and HelloWWW3.java (Chapter 2) in order to download them to that directory. Compile HelloWWW3.java and copy both HelloWWW3.class and ServletUtilities.class to tomcat_install_dir\webapps\ROOT\WEB-INF\classes\coreservlets. The easiest way is to just copy the entire coreservlets directory into tomcat_install_dir\webapps\ROOT\WEB-INF\classes. Do this by using the right mouse to drag the coreservlets directory onto the shortcut to the WEB-INF\classes directory and selecting Copy. Verify that the process works by invoking http://localhost/servlet/coreservlets.HelloWWW3.
3. 4.
5.
Create a subdirectory called exercise1 within C:\Servlets+JSP, put a simple servlet in it (be sure to have the package name correspond to the directory name), compile it, and copy the .class file to the appropriate location within the Tomcat directory. The easiest approach is to copy the entire exercise1 directory onto the shortcut to the WEB-INF\classes directory. If you want to use ServletUtilities, either copy ServletUtilities to your directory and change package coreservlets to package yourPackage, or (better!) add import coreservlets.* to whichever of your servlets use ServletUtilities. Create a servlet that uses a loop to output an HTML table with 25 rows. For instance, each row could contain RowX, Col1, RowX Col2, and RowX Col3, where X is the current row number.
6.
http://www.coreservlets.com
1.
Download ThreeParamsForm.html from the Core Servlets and JSP archive site and install it in tomcat_install_dir\webapps\ROOT. Load it by means of the URL http://localhost/ThreeParamsForm.html. Install the ThreeParams servlet and verify that you can send data to it. Change the ThreeParams servlet to reside in your package/directory. Make appropriate changes to the form that sends data to it. Test it. Change the ThreeParams form and servlet to use POST instead of GET. If you arent very familiar with HTML, see the METHOD attribute on page 391 of Core Servlets and JavaServer Pages. What changes do you need to make to your servlet to have it accept POST instead of GET? Make a registration form that collects a first name, last name, and email address. Send the data to a servlet that displays it. Feel free to modify the ThreeParams HTML form and servlet to accomplish this. Next, modify the servlet to use a default value (or send an error message) if the user omits any of the three required parameters. Use the ThreeParams form to send data to the ThreeParams servlet that contains HTML-specific characters. Verify that this can cause malformed results. Modify the servlet to filter the strings before displaying them.
2. 3.
4.
5.
http://www.coreservlets.com
1.
Install the servlet that shows all request headers (ShowRequestHeaders). Access it from both Netscape and Internet Explorer. Remember that, since the servlet is in the coreservlets package, you have to install it in the coreservlets directory and use the URL http://hostname/servlet/coreservlets.ShowRequestHeaders. Make a tiny Web page that contains a hypertext link to the servlet that shows all request headers. What new header shows up that wasnt there previously? Remember that HTML documents (and images, JSP pages, etc.) go in tomcat-install-dir\webapps\ROOT. Write a servlet that sends a different result to Internet Explorer users than to Netscape users. If you prefer one browser over the other, feel free to have the servlet insult users of the other browser. Hint: review printout of request headers from slides. Write a servlet that checks the Referer header to know which banner ad to display. Link to it from a couple of different Web pages, and display different images depending on how the user got to the servlet. Collect images by right-clicking on them in your browser and saving them to a banner-ads subdirectory of the servers root directory (not the servers classes directory!). You can use <IMG SRC="/banner-ads/file.gif" ...> to refer to the images. Note: in Java, you insert a double quote into a String by putting a backslash in front.
2.
3. 4.
http://www.coreservlets.com
1. 2. 3. 4.
Write a servlet that sends half the users to http://home.netscape.com and half to http://www.microsoft.com. Choose at random (compare the output of Math.random() to 0.5). Write a servlet that sends Netscape users to http://home.netscape.com and Internet Explorer users to http://www.microsoft.com (or, vice versa :-). Write a servlet that returns a page not found error page (404) unless the user supplies a favoriteLanguage request (form) parameter with a value of Java. Note: some Tomcat versions incorrectly omit the user-supplied error message string. Write a servlet that generates an Excel spreadsheet. Use the appropriate MIME type from the table in the notes. Use plain text rows with entries separated by tabs (\t in a Java string). Try it from both Netscape and Internet Explorer. You need to have MS Office installed for this to work. Hint: this one is easy. Write a servlet that instructs the browser to reconnect every five seconds. Display the time (print new java.util.Date()) on each connection. Write a servlet that returns a page to Internet Explorer users saying they will be sent to http://www.microsoft.com after 10 seconds. Send them there after that timeout. Send Netscape users to http://home.netscape.com after the same delay. Youll have to read about the Refresh header in the book (page 152) to see the option of supplying a specific URL to connect to. If you are familiar with Java I/O, write a servlet that returns an image (reading it from the disk). Since you will be sending binary data, use getOutputStream instead of getWriter to get the stream that sends the image. Use the appropriate MIME type. This one is probably too hard unless you already know how to read files from disk.
5. 6.
7.
http://www.coreservlets.com
Exercises: Cookies
These exercises are longer than most. Start with one of the first four, then the last one, then come back to the others if you have time. Number five is easy if youve done number one; number four is easy if youve done number two.
1. 2.
Make a servlet that says Welcome aboard to first-time visitors and Welcome back to repeat visitors. First verify that it works within a browsing session, then quit your browser and restart to verify that the cookie is persistent on disk. Write a servlet that displays the values of the firstName, lastName, and emailAddress request parameters. If a parameter is missing and the client is a first-time visitor, have the servlet list Unknown for the missing values. If a parameter is missing and the client is a repeat visitor, have the servlet use previously-entered values for the missing values. Make a servlet that keeps per-client access counts. That is, have it print This is visit number x to this page. Visit it several times each with Netscape and Internet Explorer to verify that it is keeping separate counts for each. Make an HTML form that lets you send a background color and foreground color to a servlet that displays a Web page in those colors. If you go straight to the servlet without going through the HTML form, have the servlet use cookie values to provide reasonable default color choices (i.e., your previous choice if you made one). If you arent too familiar with HTML, you set the colors as follows: <BODY BGCOLOR="colorName" TEXT="colorName"> or <BODY BGCOLOR="#RRGGBB" TEXT="#RRGGBB"> (where R, G, and B are hex values for the red, green and blue components. I.e., #FF00FF is magenta -- 255 for red, 0 for green, and 255 for blue). Repeat exercise number one, but with session cookies, not persistent cookies. Visit it twice in Internet Explorer, then click on the IE icon on the desktop to start a new browser. Is this considered the same session or a new one? Repeat the process with Netscape. Notice that they work differently. Check out your cookie files in IE and Netscape. On IE, start at the Tools menu, then do Internet Options, General, Settings, View Files. It is easier to find the cookie files if you do Delete Files first. On Netscape, do a search (Find) for a file called cookies.txt in a Netscape folder. See if you notice a cookie from doubleclick.net in both cases. Take a look at the structure of these files to see if you can figure out how they represent the various cookie parameters.
http://www.coreservlets.com
3. 4.
5.
6.
3.
4.
2. 3.
http://www.coreservlets.com
3.
4. 5. 6.
7. 8.
2.
3. 4. 5.
6.
http://www.coreservlets.com
Suppose that you have two different JSP pages that do two different things. However, for both pages you want to let the user supply a bgColor attribute to set the background color of the page. Implement this, but use an include mechanism to avoid repeating code. Hint: when you use jsp:include, the included page has the same request object as the main page. For example: White background: http://host/path/page1.jsp White background: http://host/path/page2.jsp Red background: http://host/path/page1.jsp?bgColor=RED Yellow background: http://host/path/page2.jsp?bgColor=YELLOW
Make two separate JSP pages that have bulleted lists containing random integers in a certain range. Avoid repeating code unnecessarily by including a page that defines the randomInt method from the exercise on JSP scripting expressions. The value of the page attribute of jsp:include is allowed to be a JSP expression. Make a JSP page that includes a good news page or a bad news page at random. If you are familiar with applets, make a trivial one that does nothing but set the background color to blue and print a string derived from the MESSAGE parameter embedded in the HTML by means of a PARAM element. Convert it to a version that uses the Java Plug-In. Note that, if this runs at all, it proves that you are correctly accessing the Plug-In. You dont need to use Swing or Java2D to verify that you are using the Plug-In, since the tag generated by jsp:plugin is incompatible with the standard virtual machine used by Netscape and IE. Try both Netscape and Internet Explorer to see which (if any) of them has the Plug-In installed. Reminder: applets run on the client, not on the server. So your applets .class files cant go in the servers WEB-INF/classes directory. These .class files work the same way as for regular applets: they go in the same directory as the JSP/HTML file that uses the applet tag. The one exception is if the applets are in a package, in which case they go in a subdirectory (matching the package name) of the directory that contains the JSP file. Again, this is nothing specific to JSP, but is just the normal way applets work.
3. 4. 5.
http://www.coreservlets.com
Exercises: Beans
1.
Make a simple bean called BakedBean with two String properties: level (default value half-baked) and goesWith (default value hot dogs). Compile and test it separately (i.e., without using a servlet or JSP page). Note: if your driver class (i.e., the one that has public static void main(String[] args) {...} in it) is in a package, remember that you have to use the package name when you run it from the command line. That is, you have to do javac BeanDriver.java and then java yourPackage.BeanDriver. Make a JSP page that makes a BakedBean, sets the goesWith property to caviar, and then prints out the level and goesWith properties. Make a JSP page that makes a BakedBean, sets the goesWith property based upon the value of some request parameter, and stores the bean in the ServletContext. Make a second JSP page that displays the value. Visit the first page from Netscape only (with a request parameter that sets goesWith), then visit the second page from both Netscape and Internet Explorer. Verify that both browsers see the same value. Make a JSP page that makes a BakedBean, sets the goesWith property based upon the value of some request parameter, and stores the bean in the HttpSession object. Make a second JSP page that displays the value. Visit the first page from Netscape only (with a request parameter that sets goesWith), then visit the second page from both Netscape and Internet Explorer. Verify that the two browsers see different values.
2. 3.
4.
http://www.coreservlets.com
http://www.coreservlets.com
1.
Write a servlet that generates a random number, puts it in a bean, and forwards it to a JSP page that displays it. Use request-based bean sharing. Hint: you might want to start by simply forwarding from an empty servlet to a simple JSP page that doesnt use beans. Then, once you have the RequestDispatcher part working, you can go back and have the servlet store the bean object (request.setAttribute) and have the JSP page read it (jsp:useBean with scope="request").
2.
Write a servlet that reads the firstName and lastName request parameters. If they are both present, it forwards the user to a page that displays them. If either is missing or is an empty string, it uses previously seen values from that client. If values are still missing after that, it forwards the user to a page that tells them which parameter is missing. Use session-based bean sharing. Write a servlet that uses a request parameter to determine the desired size of a prime number. If the user asks for a particular size, it should create and store one of that size. If no size is specified, the system should use the previous prime number (if there is one). Either way, it should forward the user to a page that displays the number. Use application (servlet context) based bean sharing.
3.
http://www.coreservlets.com
Exercises: JDBC
1. 2.
Make a servlet that displays a bulleted list of the names of all shipping companies used in the Northwind example. (Table name: shippers; column name: CompanyName see the second of the screen shots from Using Metadata). Make an HTML form that collects a last name. Send the name to a servlet or JSP page. If there is an employee with that last name, show full details on him or her (just show the first employee if there are multiple people with the same name). If there is no employee with that last name, say so. See the screen shot from Access for details on the column names (table name: employees; column names firstname, lastname, title, birthdate). Make an HTML form that collects three values: a table name, a number of columns c, and a number of rows r. Send the data to a servlet or a JSP page. Display an HTML table containing the first c columns of the first r rows of the designated table. Be sure to handle the case where c or r are too big.
3.
http://www.coreservlets.com
Student Survey
1.
Please rate the following from 1 (poor) to 5 (great): Instructor: ______ Topics: ______ Handouts: ______ Exercises: ______ Book: Overall: ______ ______ Facilities: ______
2.
3.
4.
http://www.coreservlets.com