Chapter 5 Tutorials

Chapter 5 Tutorials

Required Validation

  1. Use the NetBeans project that was created in the Chapter 1 Tutorials.
  2. Download the following two ZIP files from the book's web site. Unzip them to a folder on your computer.
  3. Right-click the Libraries folder in the NetBeans project. If the folder is not visible in the project tab, then open the project properties and access the library from there.
    1. Select Add Jar/Folder
    2. Navigate to the directory that contains the downloaded JAR files.
    3. Select all four JAR files and select Open.
  4. Open the Source Packages folder.
    1. Add a class named HelperBaseCh5 to the shared package.
      1. Extend it from HelperBaseCh4.
      2. Make it an abstract class, since HelperBaseCh4 is abstract.
      3. Create a non-default constructor.
        1. It should have a parameter that is a servlet object.
        2. It should have a parameter that is a request object.
        3. It should have a parameter that is a response object.
        4. Call the super class's constructor.
      4. Declare a public member variable named errorMap that is map keyed by strings and contains strings.
      5. Add a method named getErrors that returns the error map. JSPs will use this to retrieve the error map.
      6. Add a method named clearErrors that removes everything from the error map. Use the clear() method of the map. Be sure the map is not empty before you clear it.
      7. Add a static, final member variable, named validatorFactory, of type ValidatorFactory. Initialize it with the call to Validation.buildDefaultValidatorFactory().
      8. Add a static, final member variable, named validator, of type Validator. Initialize it with the call to validatorFactory.getValidator().
      9. Add a method named setErrors that has a parameter that is an object.
        1. Add a variable named violations that is a Set, containing ConstraintViloation<Object>. Initialize it with a call to validator.validate(data), where data is the name of the parameter that was passed to the method.
        2. Clear the error map variable.
        3. Fill the error map with the information from the validation messages. It is best to grab this block of code from the source code on the book's web site.
      10. Create a boolean method named isValid that has a parameter that is an object.
        1. Call the setErrors method with the parameter.
        2. Return true if there are no errors; otherwise, return false.
    2. Create a new package named ch5.requiredValidation.
      1. Copy the controller class and the controller helper class from the Enhanced tutorial for Chapter 4. Refactor as necessary.
      2. Copy the edit, confirm and process pages from the Enhanced tutorial for Chapter 4 into this package.
      3. Copy the RequestData bean from the Data Bean tutorial in Chapter 3. Rename the bean to RequestDataRequired.
    3. Modify the bean.
      1. Integer Property
        • Add an integer property that will hold the number of days per week to practice the hobby.
        • Add the Min annotation.
          1. javax.validation.constraints.Min
          2. The Min annotation is only for accessors that return a numer.
          3. Validate that the integer is greater than or equal to 1.
        • Add the Max annotation.
          1. javax.validation.constraints.Max
          2. The Max annotation is only for accessors that return a numer.
          3. Validate that the integer is less than or equal to 7.
      2. String Properties
        • Add the Pattern annotation to each string accessor. Do not add it to the integer property.
          1. javax.validation.constraints.Pattern
          2. The Pattern annotation is only for accessors that return a string.
          3. Try to validate that the string contains at least one word of letters and numbers. There could be more than one word.
        • Add the NotNull annotaion to each string accessor. Do not add it to the integer property.
          1. The NotNull annotation is only for accessors that return an object. It won't work for accessors that return numbers.
    4. Modify the controller helper.
      1. Extend the class from HelperBaseCh5.
      2. Change all bean references to the bean for this package.
      3. Remove the import for the bean from ch3.
      4. Change the location of the JSPs to this package.
      5. In the confirm method, if the data is valid, proceed to the confirm page; otherwise, return to the edit page.
    5. Modify the edit page.
      1. Add a new text box for the number of days per week to practice the hobby.
      2. Initialize it with its value from the bean.
      3. Add error messages for each property.
      4. The error message will appear when the data is invalid.
    6. Modify the confirm and process pages.
      1. Eche the value of the integer property in each page.
  5. Edit the web.xml file.
    1. Add a servlet definition for the controller.
      • Add an initialization parameter for the log name to use, if you do not want to use the default name.
      • Add an initialization parameter for the log level to use, if you do not want to use the default level.
    2. Add a servlet mapping for the controller.
    3. Do not create servlet definitions or servlet mappings for any of the other files in the package.
  6. Modify the index.jsp file.
    1. Modify the page by adding a hypertext link to the controller.
    2. Do not link to the edit page; all accesses should be to the controller.
  7. Run the project.
    1. The index.jsp page will appear in the browser.
    2. Do not enter any data and hit the button.
    3. Error messages will appear on the page.
    4. Enter valid data into one of the fields and hit the button.
    5. Only one error message will appear.
    6. Enter valid data into both fields and hit the button.
    7. You proceed to the confirm page.
  8. Validate that all the JSP files contain valid HTML.
  9. Be sure that the logger is working for this application.
  10. Whenevere a log file is used. you will need to shut down Tomcat in NetBeans before doing a clean and build.
    1. Click the Services tab in the NetBeans project.
    2. Open the Servers folder.
    3. Right-click Apache Tomcat.
    4. Click Stop.
    5. Now you can do a clean and build.

Post

  1. Open the Source Packages folder.
    1. Create a new package named ch5.postServlet.
      1. Copy the controller class and the controller helper class from the Required Validation tutorial. Refactor as necessary.
      2. Copy the edit, confirm and process pages from the Required Validation tutorial.
    2. Modify the controller.
      1. Add a doPost method.
        1. Except for the name, the method has the same signature as doGet.
        2. Create a controller helper object and call its doPost method.
    3. Modify the controller helper.
      1. Add an import for the bean from the Required Validation tutorial.
      2. Change the location of the JSPs to this package.
      3. Add a doPost method.
        1. The method should have no parameters.
        2. The method should throw IOException and ServletException.
        3. Copy the contents of the doGet method.
      4. Modify the doGet method.
        1. Do not read the old data from the session.
        2. Always call the edit method, regardless of the button that is clicked.
    4. Modify the JSPs.
      1. Add a method attribute to each form.
      2. Set the method to POST.
  2. Edit the web.xml file.
    1. Add a servlet definition for the controller.
      • Add an initialization parameter for the log name to use, if you do not want to use the default name.
      • Add an initialization parameter for the log level to use, if you do not want to use the default level.
    2. Add a servlet mapping for the controller.
  3. Modify the index.jsp file.
    1. Modify the page by adding a hypertext link to the controller.
    2. Do not link to the edit page; all accesses should be to the controller.
  4. Run the project.
    1. The index.jsp page will appear in the browser.
    2. Enter data and click each button in the application.
    3. Notice that the data does not appear in the query string in the URL.
    4. Navigate to the confirm page and reload the page in the browser.
    5. You will be asked if you want to send the data again. This is what happens when you reload a page that uses POST.
    6. Return to the edit page.
    7. Place the mouse into the location box in the browser and hit enter.
    8. A GET request has been initiated, so the old data is not read. There will be no data in the input elements.
  5. Validate that all the JSP files contain valid HTML.
  6. Be sure that the logger is working for this application.
  7. Whenevere a log file is used. you will need to shut down Tomcat in NetBeans before doing a clean and build.
    1. Click the Services tab in the NetBeans project.
    2. Open the Servers folder.
    3. Right-click Apache Tomcat.
    4. Click Stop.
    5. Now you can do a clean and build.

Persistent Data

  1. If you have not already done so in an earlier tutorial, download and unzip the two zip files from the book's web site.
    1. hibernate zip
    2. non-hibernate zip
  2. If you have not already done so in an earlier tutorial, right-click the Libraries folder in the NetBeans project. If the folder is not visible in the project tab, open the project properties and access the library from there.
    1. Select Add Jar/Folder
    2. Navigate to the directory that contains the unzipped JAR files.
    3. Select all the JAR files and select Open.
    4. Do not add the folder or the zip file, you must add each JAR file separately.
  3. Right-click the Libraries folder in the NetBeans project. If the folder is not visible in the project tab, open the project properties and access the library from there.
    1. Select Properties.
    2. There are duplicates entries for some of the JAR files, since they were added previously. Remove the duplicates.
  4. Open the Source Packages folder.
    1. Add a class named HibernateHelper to the shared package. Copy the contents from the book's web site.
    2. Add a class named PersistentBase to the shared package. Copy the contents from the book's site.
    3. Add a class named WebappListener to the shared package. Copy the contents from the book's site.
      1. It closes the Hibernate factory.
      2. It will closes the database drivers.
      3. This is very important; it reduces memory leaks in Java.
    4. Create a new package named ch5.persistentData.
      1. Copy the controller class and the controller helper class from the Post tutorial. Refactor as necessary.
      2. Copy the edit, confirm and process pages from the Post tutorial.
      3. Copy the bean from the Required Validation tutorial. Rename it to RequestDataPersistent.
    5. Modify the bean.
      1. Add the class annotation that indicates that the class will have a separate table in the database. Use the one from javax.persistence.
      2. Add a private property named id of type Long to the bean.
        1. Create a public accessor and a protected mutator for the property.
        2. Add annotations to the accessor that mark the property as a key field and that the value of the field will be maintained by Hibernate.
      3. Mark any properties that should not be saved in the database with the appropriate annotation.
    6. Modify the controller helper.
      1. Change all bean references to the bean for this package.
      2. Change the location of the JSPs to this package.
      3. Add a public, static method named initHibernate that has a servlet parameter.
        1. Add a local variable of type java.util.Properties.
        2. Set the properties for Hibernate. Copy all the properties from the book's example and change the following.
          1. Set the database dialect.
          2. Set the server.
          3. Set the port.
          4. Set the database.
          5. Set the username.
          6. Set the password.
        3. Retrieve the initialisation parameter named create that will be defined in web.xml.
        4. Parse it as a boolean.
        5. If the boolean parameter is true, then call createTable from HibernateHelper. Pass the properites and the class of the bean.
        6. Call initSessionFactory from HibernateHelper. Pass the properites and the class of the bean.
      4. Modify the process method.
        1. Validate that the data is still valid.
        2. If the data is not valid,
          1. Direct the user to an error page that explains that the session has expired.
          2. You will need to add that page to the package.
        3. If the data is valid,
          1. Write the bean to the database.
          2. Retrieve a list containing all the data from the database.
            1. Place the list of data in the request for access by the JSPs.
            2. It is important that this is placed in the request and not the session.
    7. Modify the controller. Add an init method with no parameters.
      1. Call the static method initHibernate from the controller helper, passing the servlet as a parameter.
    8. Modify the process page.
      1. Add a form that uses the GET method and goes to the edit page. Name the button New.
      2. Add the taglib for the JSTL.
      3. Add a forEach loop that displays all the data from the database.
        1. Use EL to retrieve the data using the name that was used to add the data to the request in the process method.
        2. Display each row on a separate line.
        3. List all the data for each row, separated by commas.
  5. Edit the web.xml file.
    1. Add a listener tag.
      1. Set the listener class to shared.WebappListener.
      2. This will make sure that Hibernate and the database drivers release resources when the web application is removed from memory. It is essential for minimizing memory leaks in Java.
    2. Add a servlet definition for the controller.
      1. Add an initialisation parameter named create.
      2. Set the value to true when you want to create the table; otherwise, leave it as false.
      3. Add an initialization parameter for the log name to use, if you do not want to use the default name.
      4. Add an initialization parameter for the log level to use, if you do not want to use the default level.
    3. Add a servlet mapping for the controller.
  6. Modify the index.jsp file.
    1. Modify the page by adding a hypertext link to the controller.
    2. Do not link to the edit page; all accesses should be to the controller.
  7. Run the project.
    1. The index.jsp page will appear in the browser.
    2. Enter some data and navigate to the process page.
    3. You will see a list of all the data that you have entered.
    4. Click the Edit button.
    5. Change the values and navigate to the process page.
    6. You will see that the data for the last record was changed, instead of a new record being added.
    7. Click the New button.
    8. Enter some new data and navigate to the process page.
    9. You will see that a new record has been added to the database.
    10. Be sure that the create parameter in the web.xml file is set to false, so that your table will not lose all its data when the servlet engine restarts.
    11. Navigate to the confirm page.
    12. In the browser, remove the cookie for JSESSIONID that is associated with localhost.
    13. You should still be on the confirm page. Click process. You will be redirected to the error page, since the session is no longer accessible and the data is gone.
  8. Validate that all the JSP files contain valid HTML.
  9. Whenever a log file is used. you will need to shut down Tomcat in NetBeans before doing a clean and build.
    1. Click the Services tab in the NetBeans project.
    2. Open the Servers folder.
    3. Right-click Apache Tomcat.
    4. Click Stop.
    5. Now you can do a clean and build.

Configuration File

  1. Open the Source Packages folder.
  2. Create a package named ch5.persistentData.configure.
  3. Copy the controller from ch5.persistentData into this package.
  4. Create a new controller helper.
    1. Extend the class from ch5.persistentData.ControllerHelper.
    2. Copy the constructor from the controller helper in the ch5.persistentData package.
    3. Be sure that the member variable for the bean in the ch5.persistentData.ControllerHelper class does not have private acces.
    4. Create an initHibernate method that has a parameter for the servlet. This has the same signature as the initHibernate in the ch5.peristentData package. Add the following statements to the method:
        boolean create = 
            Boolean.parseBoolean(servlet.getInitParameter("create"));
        if (create) {
            HibernateHelper.createTable(RequestDataPersistent.class);
        }
        HibernateHelper.initSessionFactory(RequestDataPersistent.class);
      
    5. Create a doGet method. Call the doGet of the super class.
    6. Create a doPost method. Call the doPost of the super class.
  5. Create a file name hibernate.cfg.xml in the default package under source packages. If there is not a default package, then add the file to source packages directly. Add the contents of this link to the file.
    1. Change the dialect to agree with your database server.
    2. Change the driver to agree with your database server.
    3. Change the connection url for your server.
    4. Change the port for your server.
    5. Change the username for connecting to your server.
    6. Change the password for connecting to your server.
  6. Edit the web.xml file.
    1. Add a servlet definition for the controller.
      1. Add an initialisation parameter named create.
      2. Set the value to true when you want to create the table; otherwise, leave it as false.
      3. Add an initialization parameter for the log name to use, if you do not want to use the default name.
      4. Add an initialization parameter for the log level to use, if you do not want to use the default level.
    2. Add a servlet mapping for the controller.
  7. Modify the index.jsp file.
    1. Modify the page by adding a hypertext link to the controller.
    2. Do not link to the edit page; all accesses should be to the controller.
  8. Run the project.
    1. The index.jsp page will appear in the browser.
    2. Follow the same steps as were recommended for runnint the persistent controller.

Contact the author