Previous Next
Programmers Guide for Java Chapter 3 - Developing Java Enterprise Web Application

Chapter 3 - Developing Java Enterprise Web Application

With the DB Visual ARCHITECT (DB-VA) you can develop quality Java Enterprise Web Application much faster, better and cheaper. All DB-VA generated code, configuration file and persistent layer library are deployable to most application servers. DB-VA generates all Java code for accessing database. You do not need to write SQL to insert, query, update or delete the record. All code you need to program is plain Java code (e.g. OrderDAO.save(myOrder);). In this chapter we will use a simple "School System" application to show you how to generate Java code, configure your web application, creating, querying, updating and deleting objects. Again you do not need to write a single SQL statement for all the above operations. In the final section we will discuss some issues about the HTTP Session.

Figure 3.1 - Java Enterprise Web Application

The architecture of Java Enterprise Web Application with DB-VA Persistent Layer

In this chapter:

Introduction

You will develop a School System.

The School System provides the following functions:

Required Software:

Please open the SchoolSystem.vpp project file in the Chapter 3 School System.zip file. The project file contains the following diagrams. For the details about how to draw class diagram and entity relationship diagram, please see the Designer's Guide.

Class Diagram of School System:

Figure 3.2 - Class Diagram of School System

Entity Relationship Diagram of School System:

Figure 3.3 - ERD of School System

Configuring Web Application Deployment Descriptor

Each Java Web Application has Web Application Deployment Descriptor (web.xml) to configure the deployment and startup of the web application. Please select "Web Application Deployment Descriptors (web.xml)" option to generate the web.xml for your web application.

  1. From menu bar, select Tools > Object-Relational Mapping (ORM) > Generate Code... to open the Database Code Generation dialog box.
  2. Figure 3.4 - To generate code
  3. Fill in code generation information.
  4. Code tab:

    For Generate, select Code and Database to generate code and create database option.

    For Language, select Java language.
    For Output Path, select the JBOSS_HOME_DEPLOY_FOLDER\schoolsystem.war\WEB-INF

     

    For example:

    C:\DevelopApps\jboss-4.0.3SP1\server\default\deploy\schoolsystem.war\WEB-INF\

    For Deploy To, select JBoss Application Server, DB-VA will help you to select the optimize option Jar to create orm.jar (persistent library).
    For Association Handling, select Smart.
    For Persistent API, select Factory Class.
    For Sample, check Sample and Servlet Sample.
    Select Web Application Deployment Descriptors (web.xml) to generate web.xml with filter configure.
    Figure 3.5 - Generate code configure for generate web application

    Database tab:

    You can reference Chapter 1 to select export the database schema and configure the default database of JDBC connection.

  5. The code is generated to JBOSS_DEPLOY_FOLDER\schoolsystem.war\.
  6. Start Eclipse Platform, create new Java project
  7. Figure 3.6 - Creatae a new Eclipse project
  8. Enter new project information.
  9. For Project name, Enter "School System"

    Select Create project from existing source. In Directory, select the JBOSS_DEPLOY_FOLDER\schoolsystem.war folder.

    Click Next >.

    Figure 3.7 - Select directory of the generated code
  10. Modify the Default output folder to /School System/WEB-INF/classes.
  11. Figure 3.8 - Select the output path and src path
  12. Click Finish to create the project. In Package Explorer, right click School System and select Properties.
  13. Figure 3.9 - Open the project properties
  14. Select Java Build Path > Libraries > Add External JARs...
  15. Figure 3.10 - Add an external Jar
  16. Select javax.servlet.jar in JBOSS_SERVER\client folder
  17. Figure 3.11 - Select the external Jar
  18. Right click WEB-INF\src\WEB-INF\web.xml to select Refactor > Move...
  19. Figure 3.12 - To move the file
  20. Select move to School System\WEB-INF.
  21. Figure 3.13 - Select the destination directory
  22. Open the web.xml file which contains the filter information of filter class and filter mapping
  23. <?xml version="1.0" encoding="ISO-8859-1"?>

    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    <display-name>SchoolSystem</display-name>
    <description>SchoolSystem</description>
    <filter>
    <filter-name>ORMFilter</filter-name>
    <filter-class>school.SchoolSystemFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>ORMFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

Creating Object and Saving to Database

The school system provides a separate register page for teacher and student to enter their information. The register method of teacher and student method is the same, so we will demonstrate how to create the teacher and save to database.

  1. Create "teacherreg.html" for teacher to input their personal information and register to the system. The submit information will be processed by CreateUser Servlet to add new user.
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Teacher Register</title>
    </head>
    <body>
    <h2>Teacher Register</h2>
    <hr>
    <form action="servlet/createUser" method="post">
    <table border="0">
    <tr><td><strong>User ID : </strong></td><td><input name="loginID" type="text" id="loginID"/></td></tr>
    <tr><td><strong>Teacher Full Name : </strong></td><td><input name="name" type="text" id="name"/></td></tr>
    <tr><td><strong>Password : </strong></td><td><input name="password" type="text" id="password"/></td></tr>
    <tr><td><strong>Email : </strong></td><td><input name="email" type="text" id="email"/></td></tr>
    <tr><td></td><td><input type="submit" name="Submit" value="Submit"></td></tr>
    </table>
    <input name="userType" type="hidden" value="teacher"/>
    </form>
    </body>
    </html>

    Source File : School System\teacherreg.html

    Figure 3.14 - The teacherreg.html view in browser
  3. Create the Servlet CreateUser.java in WEB-INF\src folder in util package to create the teacher record in system and provide the unique user ID.
  4. Configure the CreateUser.java Servlet in web.xml. After saved the web.xml, you can use /servlet/createUser to call the CreateUser.java Servlet.
  5. ...
    <servlet>
    <servlet-name>CreateUser</servlet-name>
    <servlet-class>util.CreateUser</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>CreateUser</servlet-name>
    <url-pattern>/servlet/createUser</url-pattern>
    </servlet-mapping>
    ...

    Source File : School System\WEB-INF\web.xml

  6. When you submit the form the Teacher object will be added to the database. The new user object is added to the Session. If user attribute exists in session, the user is login to the system.
  7. request.getSession().setAttribute("user", lUser);
    Figure 3.15 - The successful message
Figure 3.16 - The record is added to database

Querying Object from Database

You can retrieve the record in database as object. For example, you need to create the login function for the School System. You will require the user to input the User ID and password to login, the system retrieve the User object from the user id and compare the password to validate the user.

  1. Create the Login page (login.jsp). It submits the form to the Login Servlet. If user has login, it will redirect the user to student page or teacher page depends on the user type.
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Login Page</title>
    </head>
    <body>
    <%
    school.User lUser = (school.User)request.getSession().getAttribute("user");
    if (lUser == null){
    %>
    <h2>Login</h2>
    <hr>
    <form action="servlet/login" method="post">
    <table border="0">
    <tr><td><strong>Login ID : </strong></td><td><input name="id" type="text" id="id"/></td></tr>
    <tr><td><strong>Password :</strong></td><td><input name="password" type="password" id="password"/></td></tr>
    <tr><td></td><td><input type="submit" name="Submit" value="Submit"></td></tr>
    </table>
    </form>
    <%
    } else if (lUser instanceof school.Student){
    response.sendRedirect("studentPage.jsp");
    } else if (lUser instanceof school.Teacher){
    response.sendRedirect("teacherPage.jsp");
    }
    %>
    </body>
    </html>

    Source File : School System\login.jsp

    Figure 3.17 - The login.jsp view in browser
  3. Use User ID to call loadUserByORMID() method to retrieve the User object in Login Servlet and compare the password
  4. if (lUser != null && lUser.getPassword().equals(lPassword)) {
    request.getSession().setAttribute("user", lUser);
    if (lUser instanceof Student) {
    response.sendRedirect("../studentPage.jsp");
    } else {
    response.sendRedirect("../teacherPage.jsp");
    }
    }

    Source File : School System\WEB-INF\src\util\Login.java

Updating Object and Saving to Database

You can modify the teacher information and update the record in database. You get the User object from the session and set the new values for the User object, finally call save() method to update the record in database.

  1. Click modify info link on the Teacher Page
  2. Figure 3.18 - The teacherPage.jsp
  3. Modify the information in modifyuser.jsp. Get the User object from session and set the information to field and allow the user to modify the information, finally submit the form to the ModifyUser Servlet.
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>
    <head>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Modify Information</title>
    </head>
    <body>
    <%
    boolean isStudent = false;
    Object lUserObj = request.getSession().getAttribute("user");
    if (lUserObj == null){
    response.sendRedirect("login.jsp");
    } else {
    school.User lUser = (school.User)lUserObj;
    %>
    <form action="servlet/modifyUser" method="post">
    <table border="0">
    <tr><td>Name : </td><td><input name="name" type="text" id="studentName" value="<%= lUser.getName() %>"/></td></tr>
    <tr><td>Password :</td><td><input name="password" type="text" id="password" value="<%= lUser.getPassword() %>"/></td></tr>

    <% if (lUser instanceof school.Teacher){ %>

    <tr><td>Email :</td><td><input name="email" type="text" id="email" value="<%= ((school.Teacher)lUser).getEmail()%>"/></td></tr>

    <%} %>

    <tr><td></td><td><input type="submit" name="Submit" value="Submit"></td></tr>
    </table>
    </form>
    <% }%>
    </body>
    </html>

    Source File : School System\modifyUser.jsp

    Figure 3.19 - The password of user changed
  5. The ModifyUser Servlet get the modified information from the submitted form and set to the User object and call save() method to update the record in database. It is similar to create user.
  6. private boolean modifyUser(HttpServletRequest request,
    HttpServletResponse response, Object aUserObj) throws PersistentException {
    PersistentTransaction t = SchoolSystemPersistentManager.instance().getSession().beginTransaction();
    boolean lSuccess = false;
    try {
    String lUserName = request.getParameter("name");
    String lPassword = request.getParameter("password");
    if (lUserName != null && lUserName.length() > 0 && lPassword != null && lPassword.length() > 0) {
    User lUser = (User) aUserObj;
    lUser.setName(lUserName);
    lUser.setPassword(lPassword);
    if (lUser instanceof Teacher) {
    ((Teacher) lUser).setEmail(request.getParameter("email"));
    }
    lUser.save();
    lSuccess = true;
    } else {
    lSuccess = false;
    }
    t.commit();
    } catch (Exception e) {
    e.printStackTrace();
    t.rollback();
    }
    return lSuccess;
    }

    Source File : School System\WEB-INF\src\util\ModifyUser.java

Deleting Object in Database

Teacher can create course for students for registration and they can cancel the course in the system. They only need to click cancel hyperlink of the course then the course information will be deleted in the database and all its relationship with registered students will be removed.

  1. Teacher can create the course by selecting Create Course hyperlink in teacher page. Fill in Course name and Description to create Course.
  2. Figure 3.20 - Create course
  3. Student can register the course in the student page.
  4. Figure 3.21 - Student Page
  5. The teacher can view how many students have registered his course and he can cancel the course.
  6. Click Cancel of a Course then it will pass the course id to the DeleteCourse Servlet. The DeleteCourse Servlet contains dropCourse method which uses the Course ID to retrieve to Course Object.
  7. private void dropCourse(HttpServletRequest request)throws PersistentException{

    String lID = request.getParameter("courseID");

    PersistentTransaction t = SchoolSystemPersistentManager.instance().getSession().beginTransaction();

    try{

    Course lCourse = CourseFactory.loadCourseByORMID(Integer.parseInt(lID));
    ...

    Source File : School System\WEB-INF\src\util\DeleteCourse.java

  8. Call deleteAndDissociate() method to delete the course object and remove the relationships of student and teacher with the course.
  9. lCourse.deleteAndDissociate();

    t.commit();

    }catch(Exception e){

    e.printStackTrace();

    t.rollback();

    }

    }

    Source File : School System\WEB-INF\src\util\DeleteCourse.java

Using Persistent Object with HttpSession

here are mainly two kinds of Object in Web Application (Persistent Object and HttpSession Object). Persistent Object is used to store and retrieve data to and from the database (long term persistent media). HttpSession Object is used to store the information when the user is using the web application (usually store in RAM for short term persistent). If you need to use the Persistent Object as HttpSession Object (the lUser in the example code below), please make sure you have used the generated web.xml or configured your web application according to our generated web.xml. For more details about how to use the web.xml, please refer to previous section. 

In School System, you have put the User persistent object in HttpSession to determine the user is login or not.

Set User Object to Session:

request.getSession().setAttribute("user", lUser);

Get User Object From Session:

Object lUserObj = request.getSession().getAttribute("user");


Previous Next
Visual Paradigm International Limited
Website: www.visual-paradigm.com
E-mail: support@visual-paradigm.com