Home arrow Java arrow Page 3 - JavaServer Pages, conclusion
JAVA

JavaServer Pages, conclusion


If you've taken a look at J2EE and JavaServer Pages technology, and want to examine JSP more closely, you've come to the right place. This article is the second of two parts, excerpted from chapter three of Beginning J2EE 1.4 From Novice to Professional, written by James L. Weaver, Kevin Mukhar, and Jim Crume (Apress, 2004; ISBN: 1590593413).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 17
November 10, 2005
TABLE OF CONTENTS:
  1. · JavaServer Pages, conclusion
  2. · The config Object
  3. · Try It Out: Using JavaBeans in JSP Pages
  4. · Translation and Compilation
  5. · The Deployment Descriptor
  6. · Including and Forwarding from JSP Pages
  7. · Summary

print this article
SEARCH DEVARTICLES

JavaServer Pages, conclusion - Try It Out: Using JavaBeans in JSP Pages
(Page 3 of 7 )

In this example, we will expand the earlier example. This example will add a registration page to the application. Using the registration page, we will see some examples of using a JavaBean in the page. This example will also use the implicit request object to read request parameters.

  1. Here is the application structure for this example:

    Ch03/
      registration.jsp
      registrationform.html
      welcome.jsp
      WEB-INF/
       
    errorPage.jsp
        footer.jspf
        web.xml
        classes/
         
    Ch03/
            FaqCategories.java
            User.java
            FaqCategories.class
            User.class
  2. Start by creating the JavaBean. This bean consists of a class called User, and represents a user of our application. After entering the source, compile it into a class file:

    package Ch03;
    public class User {
      private String firstName;
      private String surname;
      private String loginName;
      private int age;
     
    public String getFirstName() { return firstName; }
      public void setFirstName(String newFirstName) {
        this.firstName = newFirstName;
      }
     
    public String getSurname() { return surname; }
      public void setSurname(String newSurname) {
        this.surname = newSurname;
      }
     
    public String getLoginName() { return loginName; }
      public void setLoginName(String newLoginName) {
        this.loginName = newLoginName;
      }
      public int getAge() { return age; }
      public void setAge(int newAge) {
       
    this.age = newAge;
      }
    }

  3. Next, well modify welcome.jsp from the earlier example. This page will ask users to register, if they havent already done so:

    <%@ page errorPage="/WEB-INF/errorPage.jsp" 
        import="java.util.Iterator,Ch03.*" %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>Java FAQ Welcome Page</title>
      </head>
     
    <body>
        <h1> Java FAQ Welcome Page</h1>
    <%
      User user = (User) session.getAttribute("user");
      if (user == null) {
    %>
        You are not yet registered, please
        <a href="registrationform.html">register</a>.
    <%
      } else {
    %>

        Welcome to the Java FAQ
    <%! FaqCategories faqs = new FaqCategories(); %>
    Click a link below for answers to the given topic.
    <%
       
    Iterator categories = faqs.getAllCategories();
        while (categories.hasNext()) {
          String category = (String) categories.next();
    %>
         
    <p><a href="<%= replaceUnderscore(category)
    %>.jsp"><%= category
    %></a></p>
    <%
       
    }
    %>
    <%@ include file="/WEB-INF/footer.jspf" %>
    <%
      }
    %>

      </body>
    </html>
    <%!
    public String replaceUnderscore(String s) {
      return s.replace(' ','_');
    }
    %>
  4. Next, create the registrationform.html page that collects the user information:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
    <title>Registration Page</title>
      </head>
      <body>
       
    <h1> Registration Page</h1>
       
    <form action="registration.jsp" method="POST">
          <table>
           
    <tr>
              <td align="right">First name:</td>
              <td align="left"><input type="text"

                  name="firstName" length="30"/></td>
            </tr>
            <tr>
             
    <td align="right">Surname:</td>
              <td align="left"><input type="text"

                  name="surname" length="30"/></td>
            </tr>
            <tr>
             
    <td align="right">Login Name:</td>
              <td align="left"><input type="text"

                  name="loginName" length="30"/></td>
            </tr>
            <tr>
             
    <td align="right">Age:</td>
              <td align="left"><input type="text"
                  name="age" length="5"/></td>
            </tr>
          </table>
         
    Which topics are you interested in?
          <br><input type="checkbox" name="topics"
                      value="Dates and Times">
            Dates and Times</input>
          <br><input type="checkbox" name="topics"
                      value="Strings and StringBuffers">
              Strings and StringBuffers</input>
          <br><input type="checkbox" name="topics"
                      value="Threading">
              Threading</input>
          <p><input type="submit" value="Submit"/></p>  
        </form>
      </body>
    </html>

  5. This form submits to a JSP page that gathers the form data and populates the User bean. This page is registration.jsp:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
    <title>Register User</title>
      </head>
      <body>
       
    <h1> Register User</h1>
       
    <jsp:useBean id="user" scope="session" class="Ch03.User">
          <jsp:setProperty name="user" property="*" />
        </jsp:useBean>
       
    Welcome new user, these are the values you submitted:
        <p>Your first name is <%= user.getFirstName() %>.</p>
        <p>Your last name is
          
    <jsp:getProperty name="user" property="surname" />.</p>
        <p>Your user id is
          <jsp:getProperty name="user" property="loginName" />.</p>
        <p>Your age is
          <jsp:getProperty name="user" property="age" />.</p>
        You selected these topics:
    <%
      String[] topics = request.getParameterValues("topics");
      if (topics == null) { topics = new String[] {"No topics"}; }
      for (int i = 0; i < topics.length; i++) {
    %>
        <br><%= topics[i] %>
    <%
      }
    %>
        <p>Go to <a href="welcome.jsp">Topic List Page</a></p>
        <%@ include file="/WEB-INF/footer.jspf" %>
     
    </body>
    </html>

  6. The other files for this application remain the same as before.

     

  7. Deploy this application to the server of your choice, using the same steps as in the first example in this chapter. If you want to update an existing EAR using the Deployment Tool, there are a couple of things you can do. Update the existing files by selecting the specific application in the left pane, and then selecting Tools | Update Files from the menu. If you also need to add new files, select the web application entry in the left pane, then click the Edit button on the General tab in the right pane, and add the new files (registration.jsp, registrationform.html, and User.class). Finally, redeploy the application by selecting Tools | Deploy.

     

  8. If youre using a Tomcat stand-alone and the application files are stored in the Tomcat /webapps directory, you just need to update the files and add the extra ones in this directory structure. If theyre stored outside this directory, delete the existing .war file and the /Ch03 directory in /webapps, recreate the .war file by calling jar cf Ch03.war* from the applications root directory as before, and copying this file to /webapps. Tomcat does not automatically deploy a .war file that has been replaced, so you will need to restart Tomcat.

     

  9. Enter the URL for the welcome.jsp. You should see this page in your browser: 
                                              


     

  10. Click on the register link to load the registration page.

                                                   


     

  11. Fill out the fields and check one or more of the boxes. Click the Submit button.

     

  12. Clicking the Submit button will cause the registration information to be passed to registration.jsp. That JSP will display this page:
                                                  
                           
  13. Finally, clicking the link in this page will send you to welcome.jsp again. This time, welcome.jsp will display the topic list:
                                               

How It Works

As in the first example, the entry into the application is the welcome.jsp page. However, this time, the page checks for the existence of a User object in the session using this code:

  User user = (User)session.getAttribute("user");

Recall that all JSP pages have access to the implicit session object, unless specified otherwise with the page directive. Using the getAttribute() method, the page attempts to get the named object from the session. Notice that getAttribute() returns a reference of type Object, which must be cast to the proper type to assign it to the user variable.

If there is no user object in the session (that is, if user is null), welcome.jsp outputs the HTML with a link for the registrationform.html page. Later, when returning to this page, the user object will exist, and the welcome page displays the topic list. The remainder of this page is unchanged.

The registrationform.html page is a standard web page with a form that submits form data to the server. The resource that it submits to is given in the <form> tag:

  <form action="registration.jsp" method="POST">

The action attribute contains the URI for the server resource that should receive the data. This URI can be relative as shown, or absolute. The method attribute indicates which HTTP method should be used for the submission. The form includes some text fields and some checkboxes. The form submits all its data to registration.jsp.

The first interesting thing about registration.jsp is the <jsp:useBean> tag shown here:

  <jsp:useBean id="user" class="Ch03.User">
    <jsp:setProperty name="user" property="*" /> 
  </jsp:useBean>

This tag creates an instance of the class given by the class attribute. Throughout the rest of the page, the object can be referred to using the variable user. Enclosed within the <jsp:useBean> element is a <jsp:setProperty> element. This element uses the property="*" attribute, which causes the page to find each setXXX method of the given bean, and call each method with the same named parameter in the request. If you look at the User class, you will see it has four public setXXX methods: setFirstName(String), setSurname(String), setLoginName(String), and setAge(int). These methods must be matched by four request parameters. If you examine registrationform.html, you will see that it does have four form fields with the correct names: firstName, surname, loginName, and age. The value from each of these request parameters is used to set the properties of the User bean.

You may recall that the <jsp:setProperty> tag also has an attribute named param. This attribute is used when the names in the request do not match the names in the bean. For example, suppose that the web page form had a field lastName instead of surname and that you were not allowed to change the web form or the bean. The JSP could not use the property="*" syntax, because the JSP is not able to match request parameters to bean properties in this case. The way to set the properties would be to use this syntax:

  <jsp:useBean id="user" class="Ch03.User">
   
<jsp:setProperty name="user" property="surname" 
  param="lastName"/>

  </jsp:useBean>

Using this syntax, the page knows that it can set the beans surname property using the value of the request parameter called lastName.

Although it is shown enclosed within the <jsp:useBean> element, you can use <jsp:setProperty> any time after the bean is created.

Next, registration.jsp stores the newly created bean in the implicit session object. This makes it available to every component in the application. Thus, when the welcome.jsp is called again, it will find the bean object.

Then the page prints out the values of the User beans properties. For the first property, a JSP expression is used to print the property. For the remainder of the properties, the <jsp:getProperty> element is used:

  <p>Your first name is <%= user.getFirstName() %></p>
  <p>Your last name is
     
<jsp:getProperty name="user"
  property="surname" />.</p>

The page then prints out the remainder of the request parameters. These are the values of the checkboxes that were checked in the form. The page calls the request.getParameterValues() method and then prints every element in the String array returned by the method. Notice that the web browser only submits values for the boxes that were checked. Finally, the JSP prints a link to the welcome.jsp page.

When welcome.jsp is called this time, the User object exists in the session, so the JSP outputs the topic list.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials