INEW 2338, Advanced Java Study Guide:  Servlets and JavaServer Pages (JSP)

Published November 8, 2004
By Richard G. Baldwin

File: Inew2338Sg004.htm


Welcome

The purpose of this series of tutorial lessons is to help you learn the essential topics covered in INEW 2338, Advanced Java.

These lessons provide questions, answers, and explanations designed to help you to understand the essential Java features covered by the Advanced Java course.

The textbook for this course is Advanced Java Internet Applications, Second Edition by Art Gittleman, ISBN 1-57676-096-0.  This study guide is for Chapter 4 in the textbook.

In addition to the textbook, I recommend that you study my extensive collection of online Java tutorial lessons.  Those tutorial lessons are published at http://www.dickbaldwin.com.

For this particular study guide, you should study lessons 660 through 695 and lessons 750 through 766 at the URL given above.

Comments Regarding the Servlet/JSP Container

Servlets

The questions in this study guide having to do with servlets assume that the class files for the servlets have been copied into the following folder in a Tomcat 5 servlet/JSP container running as a localhost server as described at http://www.dickbaldwin.com/java/Java679.htm:

c:\jakarta-tomcat-5.0.27\webapps\ROOT\WEB-INF\classes

This makes it possible to execute servlets by entering the following URL into the browser's address window:

http://localhost/servlet/ServletName

where ServletName is the name of the servlet class file without its extension.

JSP documents

Questions having to do with JSP documents assume that the JSP file has been copied into the following folder in a Tomcat 5 servlet/JSP container running as a localhost server as described at http://www.dickbaldwin.com/java/Java679.htm:

c:\jakarta-tomcat-5.0.27\webapps\ROOT

This makes it possible to cause the code in a Java Server Page to be executed by entering the following in the browser's address window:

http://localhost/JspFileName

where JspFileName is the name of the JSP file.  The name of the JSP file must include the extension .jsp.

Comments Regarding the Database Management System

Requirement for SQL database server

Some of the questions in this study guide make use of servlets along with JDBC to access an SQL database.

This study guide is written around the use of the DBMS known as MySQL.  This DBMS is compatible with a variety of platforms, and is freely available for downloading at http://www.mysql.com/.

MySQL version

More specifically, this study guide is written around the use of MySQL version 4.0.21.  It is strongly recommended that you download this version, or some version that is at least as recent as 4.0.21 but earlier than version 4.1.  At the time of preparation of this study guide, version 4.1 had not been released for production use.  However, the early release documentation indicated that there may be changes in version 4.1 that may not be backward compatible with version 4.0.21.

Unless the folks at MySQL change their policy, version 4.0.21 will continue to be available for downloading even after version 4.1 has been released for production.

MySQL server setup

The following information was extracted from the database server documentation for MySQL 4.0.21, Section 2.4.3 entitled Securing the Initial MySQL Accounts.

Part of the MySQL installation process is to set up the mysql database containing the grant tables:

The grant tables define the initial MySQL user accounts and their access privileges. These accounts are set up as follows:

As noted, none of the initial accounts have passwords. This means that your MySQL installation is unprotected until you do something about it.

Installation assumptions

All of the questions in this study guide assume that the MySQL software is installed in the default location, which is C:\mysql.  Unless the question deals with starting or stopping the server, it is assumed that the server has been started and is "ready for connections."  The questions assume that root accounts and anonymous accounts exist on the server as described above.

Unfortunately, in order to make it possible to write meaningful questions, it is sometimes necessary to assume a particular operating system for such things as directory separator symbols, etc.  In those cases, the syntax for a Windows operating system will be used.  If you are using a different operating system, you will need to translate the Windows syntax into the syntax that is appropriate for your operating system.


Questions

1.  True or False?  The servlet shown in the first box below produces the browser screen output shown in the second box.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Inew2338_050 extends HttpServlet{
  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
                    throws ServletException,
                                     IOException{

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println(
     "<HEAD><TITLE=Inew2338_050</TITLE></HEAD>");
    out.println("<BODY>");

    out.println("<h1 align=\"center\">"
                    +"<font color=\"#FF0000\">");
    out.println("Hello Big Red World");
    out.println("</font></h1>");

    out.println("</BODY></HTML>");
  }//end doGet()
}//end class Inew2338_050

Answer and Explanation

2.  True or False?  The servlet shown in the first box below produces the browser screen output shown in the second box.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Inew2338_051 extends HttpServlet{
  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
                    throws ServletException,
                                     IOException{

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println(
     "<HEAD><TITLE=Inew2338_051</TITLE></HEAD>");
    out.println("<BODY>");

    out.println("<h1 align=\"center\">"
                    +"<font color=\"#0000FF\">");
    out.println("Hello Big Green World");
    out.println("</font></h1>");

    out.println("</BODY></HTML>");
  }//end doGet()
}//end class Inew2338_051

Answer and Explanation

3.  True or False?  The JSP document shown in the first box below produces the browser screen output shown in the second box.

<!--File Inew2338_052.jsp -->

<html>
     <body>
     <H1>My First JSP Page</H1>
     <H2>Hello, JSP world!</H2>

     <% for (int i=0; i<6; i++) { %>
         <br> 
         <%= i %>
     <% }//end for loop %>

     <H3>Isn't this fun</H3>

     </body>
</html>

Answer and Explanation

4.  True or False?  The servlet shown in the first box below produces the browser screen output shown in the second box.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Inew2338_053 extends GenericServlet{
  public void service(ServletRequest req,
                    ServletResponse res)
                    throws ServletException,
                                     IOException{

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println(
     "<HEAD><TITLE=Inew2338_053</TITLE></HEAD>");
    out.println("<BODY>");

    out.println("<h1 align=\"center\">"
                    +"<font color=\"#0000FF\">");
    out.println("Hello Big Blue World");
    out.println("</font></h1>");

    out.println("</BODY></HTML>");
  }//end service()
}//end class Inew2338_053

Answer and Explanation

5.  The following box contains the code for a servlet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Inew2338_056 extends HttpServlet{
  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
            throws ServletException, IOException{

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println(
     "<HEAD><TITLE>Inew2338_056</TITLE></HEAD>");
    out.println("<BODY>");

    String firstName = req.getParameter(
                                    "firstName");
    String lastName = req.getParameter(
                                     "lastName");

    out.println(lastName + ", " + firstName);
    out.println("<BR>");
    out.println("</BODY></HTML>");

  }//end doGet()
}//end class Inew2338_056

The following box contains the text for an HTML file that incorporates a form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<HTML>

<HEAD>
<TITLE>Inew2338_056</TITLE>
</HEAD>

<body link="#0000ff" vlink="#666666" 
alink="#ff0000" lang="EN-US">
<FORM METHOD=POST 
ACTION="http://localhost/servlet/Inew2338_056">
Enter your name and press the button<P>
First Name: <INPUT TYPE=TEXT NAME="firstName"><P>
Last Name: <INPUT TYPE=TEXT NAME="lastName"><P>
<INPUT TYPE=SUBMIT> 

</BODY>

</HTML>

The following box contains an image of the browser screen after the user has accessed the HTML file in his browser and has filled in the fields, but before he has pressed the Submit Query button.

True or False?  The following box contains an image of the browser screen after the user has pressed the Submit Query button.

Answer and Explanation

6.  The following box contains the text for an HTML file that incorporates a form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<HTML>

<HEAD>
<TITLE>Inew2338_056</TITLE>
</HEAD>

<body link="#0000ff" vlink="#666666" 
alink="#ff0000" lang="EN-US">
<FORM METHOD=GET 
ACTION="http://localhost/servlet/Inew2338_056">
Enter your name and press the button<P>
First Name: <INPUT TYPE=TEXT NAME="firstName"><P>
Last Name: <INPUT TYPE=TEXT NAME="lastName"><P>
<INPUT TYPE=SUBMIT> 

</BODY>

</HTML>

The following box contains an image of the browser screen after the user has accessed the HTML file in his browser and has filled in the fields, but before he has pressed the Submit Query button.

When the user presses the Submit Query button, the browser accesses a servlet on the HTTP server.  Which of the following best describes the URL used by the browser to access the servlet? (Note that some of these lines may wrap due to the width of the browser window used to view this document.)

Answer and Explanation

7.  The following box contains the text for an HTML file that incorporates a form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<HTML>

<HEAD>
<TITLE>Inew2338_056</TITLE>
</HEAD>

<body link="#0000ff" vlink="#666666" 
alink="#ff0000" lang="EN-US">
<FORM METHOD=POST 
ACTION="http://localhost/servlet/Inew2338_056">
Enter your name and press the button<P>
First Name: <INPUT TYPE=TEXT NAME="firstName"><P>
Last Name: <INPUT TYPE=TEXT NAME="lastName"><P>
<INPUT TYPE=SUBMIT> 

</BODY>

</HTML>

The following box contains an image of the browser screen after the user has accessed the HTML file in his browser and has filled in the fields, but before he has pressed the Submit Query button.

When the user presses the Submit Query button, the browser accesses a servlet on the HTTP server.  Which of the following best describes the URL used by the browser to access the servlet? (Note that some of these lines may wrap due to the width of the browser window used to view this document.)

Answer and Explanation

8.  The following box contains the code for a servlet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Inew2338_058 extends HttpServlet{
  public void doPost(HttpServletRequest req,
                    HttpServletResponse res)
            throws ServletException, IOException{

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println(
     "<HEAD><TITLE>Inew2338_058</TITLE></HEAD>");
    out.println("<BODY>");

    String firstName = req.getParameter(
                                    "firstName");
    String lastName = req.getParameter(
                                     "lastName");

    out.println(lastName + ", " + firstName);
    out.println("<BR>");
    out.println("</BODY></HTML>");

  }//end doGet()
}//end class Inew2338_058

The following box contains the text for an HTML file that incorporates a form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<HTML>

<HEAD>
<TITLE>Inew2338_058</TITLE>
</HEAD>

<body link="#0000ff" vlink="#666666" 
alink="#ff0000" lang="EN-US">
<FORM METHOD=POST 
ACTION="http://localhost/servlet/Inew2338_058">
Enter your name and press the button<P>
First Name: <INPUT TYPE=TEXT NAME="firstName"><P>
Last Name: <INPUT TYPE=TEXT NAME="lastName"><P>
<INPUT TYPE=SUBMIT> 

</BODY>

</HTML>

The following box contains an image of the browser screen after the user has accessed the HTML file in his browser and has filled in the fields, but before he has pressed the Submit Query button.

True or False?  The following box contains an image of the browser screen after the user has pressed the Submit Query button.

Answer and Explanation

9.  The following box contains the code for a servlet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Inew2338_060 extends HttpServlet{
  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
            throws ServletException, IOException{

    try {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();

      out.println("<HTML>");
      out.println("<HEAD>");
      out.println(
           "<TITLE=Inew2338_060</TITLE></HEAD>");
      out.println("<BODY>");

      Class.forName("com.mysql.jdbc.Driver");
      String url = "jdbc:mysql://localhost/test";
      Connection con =
          DriverManager.getConnection(url,"","");
      Statement stmt = con.createStatement();

      try{
        stmt.executeUpdate(
                 "DROP TABLE Inew2338_060Table");
      }catch(Exception e){
        //No problem, just keep going.
      }//end catch

      try{
        stmt.executeUpdate(
               "CREATE TABLE Inew2338_060Table ("
                + "lastName char(15),"
                + "firstName char(15))");
      }catch(Exception e){
        out.println(e + "<br>");
        out.println(
        "Table exists, can't create it<br><br>");
      }//end catch

      String firstName = req.getParameter(
                                    "firstName");
      String lastName = req.getParameter(
                                     "lastName");

      stmt.executeUpdate(
          "INSERT INTO Inew2338_060Table ("
          + "lastName, firstName) VALUES('"
          + lastName + "','" + firstName + "')");

      ResultSet rs = stmt.executeQuery(
               "SELECT * from Inew2338_060Table "
               + "ORDER BY lastName");

      while(rs.next()) {
        lastName = rs.getString("lastName");
        firstName = rs.getString("firstName");
        out.println(lastName + ", " + firstName);
        out.println("<BR>");
      }//end while loop

      con.close();

      out.println("</BODY></HTML>");

    }catch( Exception e ) {
      e.printStackTrace();
    }//end catch
  }//end doGet()
}//end class Inew2338_060

The following box contains the text for an HTML file that incorporates a form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<HTML>

<HEAD>
<TITLE>Inew2338_060</TITLE>
</HEAD>

<body link="#0000ff" vlink="#666666" 
alink="#ff0000" lang="EN-US">
<FORM METHOD=GET 
ACTION="http://localhost/servlet/Inew2338_060">
Enter your name and press the button<P>
First Name: <INPUT TYPE=TEXT NAME="firstName"><P>
Last Name: <INPUT TYPE=TEXT NAME="lastName"><P>
<INPUT TYPE=SUBMIT> 

</BODY>

</HTML>

The following box contains an image of the browser screen after the user has accessed the HTML file in his browser and has filled in the fields, but before he has pressed the Submit Query button.

True or False?  The following box contains an image of the browser screen after the user has pressed the Submit Query button.

Answer and Explanation

10.  True or false?  The servlet shown in the following box is capable of producing the output shown below as the result of one invocation of several successive invocations.

New Session: false
Creation Time: Sat Oct 02 18:20:10 CDT 2004
Last Accessed: Sat Oct 02 18:32:54 CDT 2004
Current Time: Sat Oct 02 18:37:21 CDT 2004

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Inew2338_062 extends HttpServlet{
  PrintWriter out;

  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
            throws ServletException, IOException{

    res.setContentType("text/html");
    out = res.getWriter();

    HttpSession ses = req.getSession(true);

    out.println("<HTML>");
    out.println(
              "<HEAD><TITLE>Inew2338_062</TITLE>"
              + "</HEAD>");

    out.println("<BODY>");
    out.println("New Session: " + ses.isNew()
                                       + "<BR>");

    out.println("Creation Time: "
               + new Date(ses.getCreationTime())
               + "<BR>");
    out.println("Last Accessed: "
           + new Date(ses.getLastAccessedTime())
           + "<BR>");
    out.println("Current Time:  "
           + new Date() + "<BR>");

    out.println("</BODY></HTML>");
  }//end doGet()

}//end class Inew2338_062

Answer and Explanation



Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com


Answers and Explanations


Answer 10

True.

Explanation 10

This servlet provides an example of session tracking.  The session tracking capability makes it possible for a servlet to keep track of various kinds of information related to successive invocations from individual clients, such as the contents of a shopping cart belonging to each client.

You can learn more about this topic in lesson 691 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 10


Answer 9

True.

Explanation 9

This question illustrates what is sometimes called a three-tier system.  A browser causes a servlet on a server to be executed.  The servlet gets input data from the browser and stores that data in a database on another server.  Then it retrieves that data from the database server, formats it, and sends it back to the browser as output.

You can learn more about this topic in lesson 682 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 9


Answer 8

True.

Explanation 8

This HTML FORM sends a POST command to the servlet, which is processed by a doPost method in the servlet.

You can learn more about this topic in lesson 680 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 8


Answer 7

A.  http://localhost/servlet/Inew2338_056

Explanation 7

This HTML form uses a POST value for a METHOD attribute instead of a GET value.  This causes a POST command to be sent to the web server.  When a POST command is sent to a web server by an HTML form, the form's field values are not appended in the form of a query string to the end of the URL specified by the value of the ACTION attribute.  The form's field values are sent to the server using a different mechanism.  More data can be sent with a POST command than with a GET command.

You can learn more about this topic in lesson 680 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 7


Answer 6

B.
  http://localhost/servlet/Inew2338_056?firstName=Dick&lastName=Baldwin

Explanation 6

When an HTML FORM is used with a GET value for a METHOD attribute, a GET command is sent to the web server.  The values of the form's fields are used to create a query string, which is appended to the end of the URL specified by the value of the ACTION attribute.  These values may be accessed by the program (servlet) running on the server.  The query string is separated from the original URL by a question mark character.  Each field value is sent as a name-value pair, as in:

firstName=Dick

Individual name-value pairs in the query string are separated by ampersand characters.

You can learn more about this topic at http://www.silurian.com/sitevigil/query.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some useful publications on this topic.

Back to Question 6


Answer 5

False.

Explanation 5

The following error message is produced when the Submit Query button is pressed:

"HTTP Status 405 - HTTP method POST is not supported by this URL."

By defining the doGet method, the servlet is designed to support an HTTP GET command.  However, it is not designed to support an HTTP POST command.

To make the HTML file work correctly with the servlet, modify it to read:

<FORM METHOD=GET ...

instead of

<FORM METHOD=POST ...

You can learn more about this topic in lesson 682 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 5


Answer 4

True.

Explanation 4

Note that this servlet extends the GenericServlet class and overrides the service method, as opposed to extending the HttpServlet class and overriding the doGet method, as was the case in an earlier question.  The HttpServlet class is less general than the GenericServlet class, but for this application, you can use either approach.

You can learn more about this topic in lesson 680 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 4


Answer 3

True.

Explanation 3

This is a simple JSP document that mixes HTML text with Java source code.  The two top lines of text and the bottom line of text are produced by ordinary HTML.  The column of numbers in between is produced by the Java source code in the JSP tags.

You can learn more about this topic in lesson 750 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 3


 

Answer 2

False.

Explanation 2

This servlet produces blue letters instead of green letters as a result of the following hexadecimal color specification:

0000FF

The first pair of characters specifies the level of red, which is zero.  The second pair of characters specifies the level of green, which is also zero.  The third pair of characters specify the level of blue, which is the maximum allowable, or 255 when expressed in decimal.

You can learn more about this topic at http://www.pageresource.com/html/fonthelp.htm.

Back to Question 2


Answer 1

True.

Explanation 1

This is a simple servlet that creates HTML text in the output.  The HTML text will be rendered as shown in most browsers.

You can learn more about this topic in lesson 680 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 1


Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-