Friday, November 8, 2024

Creating Your First JSP

Now that you have a general idea of how JSPs are coded, you’re ready to learn some specific skills for creating a JSP. To start, you need to know more about coding scriptlets and expressions.

How to code scriptlets and expressions
Figure 4-4 summarizes the information you need for coding scriptlets and expressions within a JSP. To code a scriptlet, for example, you code Java statements that end with semicolons within the JSP scriptlet tags. To code an expression, you code any Java expression that evaluates to a string. Since primitive data types like integers or doubles are automatically converted to strings, you can also use expressions that evaluate to these data types.

Figure 4-4: How to code scriptlets and expressions

The syntax for a JSP scriptlet

<% Java statements %>

The syntax for a JSP expression

<%= any Java expression that can be converted to a string % >

The syntax for getting a parameter from the implicit request object

request.getParameter(parameterName);

Examples that use scriptlets and expressions

A scriptlet and expression that display the value of the firstName parameter

<%
String firstName = request.getParameter("firstName");
%>
The first name is <%= firstName %> .

An expression that displays the value of the firstName parameter

The first name is <%= request.getParameter("firstName") %>.

Two scriptlets and an expression that display an HTML line 5 times

<%
  int numOfTimes = 1;
  while (numOfTimes 

Description

  • Within a scriptlet, you can code one or more complete Java statements. Because these statements are Java statements, you must end each one with a semicolon.
  • Within a JSP expression, you can code any Java expression that evaluates to a string. This includes Java expressions that evaluate to any of the primitive types, and it includes any object that has a toString method. Because a JSP expression is an expression, not a statement, you don’t end it with a semicolon.

When you’re coding a scriptlet or an expression, you can use any of the methods of the implicit request object. In this figure, only the getParameter method is used, but you’ll learn about two more methods of the request object in the next figure.

In this figure, the first two examples show different ways that you can display the value of a parameter. The first example uses a scriptlet to return the value of the firstName parameter and store it in a String object. Then, this example uses an expression to display the value. In contrast, the second example uses an expression to display the value of the firstName parameter without creating the firstName object.

The last example in this figure shows how two scriptlets and an expression can be used to display an HTML line five times while a Java variable within the HTML line counts from 1 to 5. Here, the first JSP scriptlet contains the code that begins a while loop. Then, a line of HTML code uses a JSP expression to display the current value of the counter for the loop. And finally, the second scriptlet contains the code that ends the loop.

How to use the methods of the request object

In the last figure, you learned how to use the getParameter method to return the value that the user entered into a textbox. Now, figure 4-5 summarizes that method and illustrates it in a new context. This figure also summarizes and illustrates two more methods of the implicit request object.

Figure 4-5: How to use the methods of the request object

Three methods of the request object MethodDescription getParameter(String param)Returns the value of the specified parameter as a string if it exists or null if it doesn’t. Often, this is the value defined in the Value attribute of the control in the HTML page or JSP. getParameterValues(String param)Returns an array of String objects containing all of the values that the given request parameter has or null if the parameter doesn’t have any values. getParameterNames()Returns an Enumeration object that contains the names of all the parameters contained in the request. If the request has no parameters, the method returns an empty Enumeration object.

A scriptlet that determines if a checkbox is checked

<%
    String rockCheckBox = request.getParameter("Rock");
    // returns the value or "on" if checked, null otherwise.
    if (rockCheckBox != null){
%>
        You checked Rock music!
<%  
    }
%>

A scriptlet that reads and displays multiple values from a list box

<%
    String[] selectedCountries = request.getParameterValues("country");
    // returns the values of items selected in list box.
    for (int i = 0; i 

A scriptlet that reads and displays all request parameters and values

<%
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()){
        String parameterName = (String) parameterNames.nextElement();
        String parameterValue = request.getParameter(parameterName);
%>
        <%= parameterName %> has value 

Description

  • You can use the getParameter method to return the value of the selected radio button in a group or the selected item in a combo box. You can also use it to return the value of a selected check box or independent radio button, but that value is null if it isn’t selected.
  • If an independent radio button or a checkbox doesn’t have a Value attribute, this method returns “on” if the control is selected or null if it isn’t.

In most cases, the getParameter method returns the value of the parameter. For a textbox, that’s usually the value entered by the user. But for a group of radio buttons or a combo box, that’s the value of the button or item selected by the user.

For checkboxes or independent radio buttons that have a Value attribute, the getParameter method returns that value if the checkbox or button is selected and a null value if it isn’t. For checkboxes or independent radio buttons that don’t have a Value attribute, though, the getParameter method returns an “on” value if the checkbox or button is selected and a null value if it isn’t. This is illustrated by the first example in this figure.

To retrieve multiple values for one parameter name, you can use the getParameterValues method as illustrated by the second example. This method is useful for controls like list boxes that allow multiple selections. After you use the getParameterValues method to return an array of String objects, you can use a loop to get the values from the array.

To get the names of all the parameters sent with a request, you can use the getParameterNames method to return an Enumeration object that contains the names. Then, you can search through the Enumeration object to get the parameter names, and you can use the getParameter method to return the value for each parameter name. This is illustrated by the third example.

If you’re not familiar with the Enumeration class, you can learn more about it though the API. For most purposes, though, you only need to know that an Enumeration object is a collection that can be searched element by element. To determine if more elements exist in the collection, you can use the hasMoreElements method, which returns a boolean value. And to get the next element in the collection, you can use the nextElement method.

Where and how to save a JSP

As figure 4-6 shows, you normally save the JSPs of an application in the same directory that you use for the HTML pages of the application. The difference is that the name for a JSP requires a jsp extension. So if you’re using a text editor that’s not designed for working with JSPs, you may have to place the filename in quotation marks to make sure the file is saved with the jsp extension.

Figure 4-6: Where and how to save a JSP

Where the show_email_entry.jsp page is saved

c:tomcatwebappsmurachemail4

Other places you can save your JSPs

c:tomcatwebappsyourDocumentRoot
c:tomcatwebappsyourDocumentRootyourSubdirectory
c:tomcatwebappsROOT
c:tomcatwebappsROOTyourSubdirectory

A standard dialog box for saving a JSP

Description

  • JSPs are normally saved in the same directory as the HTML pages. This directory should be a subdirectory of the web applications directory for your server. If you’re running Tomcat on your PC, that directory is usually c:tomcatwebapps or c:jakarta-tomcatwebapps.
  • For the first 16 chapters of this book, the document root directory for all applications is the murach directory. As a result, the HTML and JSP files for each application are stored in this directory or one of its subdirectories.
  • If you’re using Tomcat on your local system, you can also use webappsROOT as the root directory for your applications. The ROOT directory is automatically set up when you install Tomcat, and it is the default document root directory.
  • To make sure that the filename for a JSP is saved with the jsp extension when you’re using an HTML or text editor, you can enter the filename within quotes.

Like HTML pages, JSPs must be saved in a directory that’s available to the web server. For Tomcat 4.0, you can use any directory under the webapps directory. The root directory for the web applications that are presented in the first 16 chapters of this book is the webappsmurach directory, and the subdirectory for the Email List application that’s presented in this chapter is email4. Note, however, that you can also use the webappsROOT directory that Tomcat sets up as the default root directory. Or, you can create your own subdirectories under the webapps directory.

How to request a JSP

After you create a JSP, you need to test it. One way to do that is to click on a link or a button on an HTML page that requests the JSP. Another way is to enter a URL into a web browser that requests the JSP. Figure 4-7 shows how to request a JSP either way.

Figure 4-7: How to request a JSP

A URL that includes parameters

Tomcat directoryURL c:tomcatwebappsmurachhttp://localhost:8080/murach/ c:tomcatwebappsmurachemail4http://localhost:8080/murach/email4 c:tomcatwebappsROOThttp://localhost:8080/ c:tomcatwebappsROOTemail4http://localhost:8080/email4

A Form tag that requests a JSP

<form action="show_email_entry.jsp" method="get" >

Two URLs that request a JSP

http://localhost:8080/murach/email4/show_email_entry.jsp
http://www.murach.com/email4/show_email_entry.jsp

How to include parameters

show_email_entry.jsp?firstName=John
show_email_entry.jsp?firstName=John&lastName=Smith

Description

  • When you use the Get method to request a JSP from an HTML form, the parameters are automatically appended to the URL.
  • When you code or enter a URL that requests a JSP, you can add a parameter list to it starting with a question mark and with no intervening spaces. Then, each parameter consists of its name, an equals sign, and its value. To code multiple parameters, use ampersands (&) to separate the parameters.

To request a JSP from an HTML form, you use the Action attribute of the form to provide a path and filename that point to the JSP. This is illustrated by the first example in this figure. Here, the assumption is that the HTML page and the JSP are in the same directory. If they weren’t, you would have to supply a relative or absolute path for the JSP file.

To request a JSP by entering its URL into a browser, you enter an absolute URL as shown by the next two examples in this figure. The first example shows the URL for the JSP when it’s stored on a local web server in the email4 directory of the murach directory. The second example shows the URL for the JSP if the JSP was deployed on the Internet server for www.murach.com.

When you test a JSP by entering a URL, you will often want to pass parameters to it. To do that, you can add the parameters to the end of the URL as shown by the last examples in this figure. Here, the question mark after the jsp extension indicates that one or more parameters will follow. Then, you code the parameter name, the equals sign, and the parameter value for each parameter that is passed, and you separate multiple parameters with ampersands (&). If you omit a parameter that’s required by the JSP, the getParameter method will return a null value for that parameter.

When you use a Get method to request a JSP from another page, any parameters that are passed to the JSP will be displayed in the browser’s URL address. In this figure, for example, you can see the first two parameters that have been attached to the URL. However, in the next figure, you’ll learn that the Post method works differently.

When to use the Get and Post methods

When you code a Form tag that requests a JSP, you can code a Method attribute that specifies the HTTP method that’s used for the request. The Get method is the default HTTP method, but the Post method is also commonly used.

Figure 4-8 presents the pros and cons of using the Get and Post methods. With either method, you can still test the page by appending the parameters to the URL string. So the question really comes down to selecting the appropriate method for the finished web application.

Figure 4-8: When to use the Get and Post methods

An HTML form tag that uses the Post method

<form action="show_email_entry.jsp" method="post">

A JSP that’s requested through the Post method

When to use the Get method

  • If you want to transfer data as fast as possible.
  • If the HTML form only needs to transfer 4 KB of data or less.
  • If it’s okay for the parameters to be displayed in the URL.
  • If you want users to be able to include parameters when they bookmark a page.

When to use the Post method

  • If you’re transferring over 4 KB of data.
  • If it’s not okay for the parameters to be appended to the URL.

Description

  • The visible difference between the Get and Post methods is the URL that’s displayed in the browser. For Get requests from an HTML page, the parameters are appended to the URL. For Post requests, the parameters are still sent, but they’re not displayed in the browser.
  • You can test a JSP that uses either method by appending the parameters to the URL.

There are two primary reasons for using the Post method. First, since the Post method doesn’t append parameters to the end of the URL, it is more appropriate for working with sensitive data. If, for example, you’re passing a parameter for a password or a credit card number, the Post method prevents these parameters from being displayed in the browser. In addition, it prevents the web browser from including these parameters in a bookmark for a page. Second, you need to use the Post method if your parameters contain more than 4 KB of data.

For all other uses, the Get method is preferred. It runs slightly faster than the Post method, and it lets the user bookmark the page along with the parameters that were sent to the page.

Excerpted from Chapter 4 of Murach’s Java Servlets and JSP

Click here to sign up for FREE Tech. newsletters from Murdok!

Joel Murach has been writing and editing for more than 10 years. During that time, he sharpened his programming skills as a contract programmer in San Francisco and his instructional skills as a trainer for HarperCollins Publishing. He always brings a vision to his projects that leads to improved effectiveness for his readers.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
0FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles

Free & easy backlink link building. Site is undergoing maintenance. Warehouse.