Top
Interstage Studio User's Guide
FUJITSU Software

4.2.3 Development Procedures

The actual procedures used to develop the application are described below.

1) Preparing the Database

2) Creating the Persistence Unit

3) Creating the Entity

4) Creating the Logic Class

5) Creating the EAR Project

6) Creating the Web Application

7) Setting the Interstage Application Server JDBC

8) Checking Application Operation

9) Distributing the Application to the Operating Environment

1) Preparing the Database

The database uses Oracle. Create the database table that stores the country name and total population data and insert the data required for execution for the application. In addition, prepare an environment that enables connection from the workbench to the database.
For details, refer to "8.2 Introduction" in "Database Operation", where these tasks are described.

2) Creating the Persistence Unit

2-1) Creating the JPA Project

Select [File] > [New] > [Project] from the menu bar. The [New Project] wizard is displayed.

Select [JPA] > [JPA Project] from the [New Project] wizard, then click [Next].

Check and enter the following setup items:

Setup items

Setup content

Project name

JPASample

Target Runtime

Interstage Application Server V11.1 IJServer Cluster (Java EE)

Configuration

Default Configuration for Interstage Application Server V11.1 IJServer Cluster (Java EE)

Set the information, then click [Next]. The [JPA Facet] age is displayed.

Check and enter the following setup items. After the following information is set, click [Finish].

Setup items

Setup content

Platform

Generic

Connection

Oracle_Studio

Override default schema from connection

Do not select.

Use implementation provided by server runtime

Select

Discover annotated classes automatically

Select

Create orm.xml

Do not select.

Point

By specifying the connection profile connected to the database at [Connection], the database table and column information can be used in the JPA Details view or similar.

2-2) Editing the persistence.xml File

In persistence.xml, code the JDBC Resource of the database associated with the Entity.
Select the created project (JPASample), then double-click [src] > [META-INF] > [persistence.xml] for the Persistence XML editor to open the file.
In the Persistence XML Editor, select the [Connection] tab, then configure the JDBC Resource as displayed below.

Setup items

Setup content

Transaction Type

JTA

JTA Data Source Name

jdbc/Oracle

3) Creating the Entity

Create the Entity that performs database table mapping.

Point

Since the method of using the JPA Structure view and the JPA Details view is described below, the method for creating a Java class and associating the database with that is described. However, an Entity can also be generated from a database table. For details, refer to "4.3.3.4 Generating Entity Classes from Tables".

3-1) Creating the Entity

Select the created project, then right-click to display the context menu. Select [New] > [Other] from the context menu. The [New] wizard is displayed.

In the [New] wizard, select [JPA] > [Entity], then click [Next].

Check and enter the following setup items.

Setup items

Setup content

Project

JPASample

Source folder

/JPASample/src

Java package

sample

Class name

CountryData

Inheritance

Entity

Add to entity mappings in XML

Do not select.

After the information is set, click [Next]. The [Entity Properties] page is displayed.

Check and enter the following setup items. After the following information is set, click [Finish].

Setup items

Setup content

Entity Name

CountryData

Use default

Do not select.

Table Name

C_DATA

Entity Fields

Add the following field

Access Type

Field-based

Key

Name

Type

Select

id

int

Do not select

countryName

java.lang.String

Do not select

totalPopulation

int

3-2) Setting the Association with the Table

Set an association between the Entity CountryData class and the database C_DATA table. Check that the CountryData class is selected in the [JPA Structure] view. In the [JPA Details] view, check that "C_DATA" is set in [Name] of the [Table] group.

Point

When not connected to the database, the combo box does not display suggestions but the table name can be specified directly.

Check and select the following setup items.

Setup items

Setup content

Name

Default (CountryData)

Table: Name

C_DATA

Table: Catalog

Default ()

Table: Scheme

STUDIO

3-3) Setting Associations with Columns

Set the associations between the Entity fields and the table columns.

Each field corresponds to a column, as shown in the table below.

Field

Association

Column: name

id

Id

ID

countryName

Basic (Default)

C_NAME

totalPopulation

Basic (Default)

T_POP

The preceding procedures create the following source.

CountryData class

package sample;

import java.io.Serializable;
import java.lang.String;
import javax.persistence.*;

/**
 * Entity implementation class for Entity: CountryData
 *
 */
@Entity
@Table(name="C_DATA", schema = "STUDIO")
public class CountryData implements Serializable {

    @Id
    @Column(name="ID")
    private int id;

    @Column(name="C_NAME")
    private String countryName;

    @Column(name="T_POP")
    private int totalPopulation;
    private static final long serialVersionUID = 1L;

    public CountryData() {
        super();
    }
    public int getId() {
        return this.id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return this.countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public int getTotalPopulation() {
        return this.totalPopulation;
    }
    public void setTotalPopulation(int totalPopulation) {
        this.totalPopulation = totalPopulation;
    }

}

4) Creating the Logic Class

Create the PopulationRanking class that performs queries to the database and so on.

4-1) Creating the Class

Select the created project and right-click to display the context menu. Select [New] > [Class] from the context menu. The [New Java Class] wizard is displayed.

Check and enter the following setup items. After the following information is set, click [Finish].

Setup items

Setup content

Source folder

JPASample/src

Package

sample

Name

PopulationRanking

4-2) Implementing the Logic Class

The Entity is managed by the javax.persistence.EntityManager class. Add the constructor set in the argument to the javax.persistence.EntityManagerFactory class that creates this class. Since the PopulationRanking class is used by the Web application servlet class, this argument is passed from the servlet class. Add the following code to the PopulationRanking class.

Constructor Addition

package sample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class PopulationRanking {
    private EntityManager em;
    
    public PopulationRanking(EntityManagerFactory factory) {
        this.em = factory.createEntityManager();
    }
}

Point

After the required implementation is coded, right-click on the Java editor, then select [Source] > [Organize Imports] from the context menu. The import statement that is appropriate for the classpath that was set in the project can then be inserted.

Add the method that fetches from the C_DATA table the total population ranking that corresponds to the ID. To fetch the CountryData class that is mapped to the C_DATA table, use the find method of the EntityManager instance. Since the table data is stored in order, starting with the largest total population, the rank and ID are the same value.

Add the following code to the PopulationRanking class.

Addition of Method for getting Total Population Ranking

public CountryData getCountryData(int rank) {
    if (rank < 1 || rank > 10) {
        return null;
    }
    CountryData country = em.find(CountryData.class, rank);
    return country;
}

5) Creating the EAR Project

Select [File] > [New] > [Project] from the menu bar. The [New Project] is displayed.

Select [Java EE] > [Enterprise Application Project] from the New Project wizard, then click [Next].

Check and enter the following setup items:

Setup items

Setup content

Project name

JPAEARSample

Target Runtime

Interstage Application Server V11.1 IJServer Cluster (Java EE)

EAR version

5.0

Configuration

Default Configuration for Interstage Application Server V11.1 IJServer Cluster (Java EE)

Set the information, then click [Next]. The [Enterprise Application] page is displayed.

Check and enter the following setup items. After the following information is set, click [Finish].

Setup Items

Setup Content

Java EE Module Dependencies

JPASample

Content Directory

EarContent

Generate deployment descriptor

Do not select.

6) Creating the Web Application

Conventionally, procedures to create a Web application as a client are needed, but with Interstage Studio a sample is imported and, if JPA is used, the important points are checked. If you want to know the detailed procedure for creating a Web application, refer to "2.2 Introduction" in "Developing Web Applications".

Use the following procedure to import a sample.
Select [File] > [Import] from the menu. Select [General] > [Existing Projects into Workspace] from the displayed Import wizard. Select [Select archive file], then click the [Browse] button and select the following files:

<Workbench installation folder>\sample\JPASample.zip

Select [JPAClientSample] from [Projects], then click [Finish].
After the JPAClientSample project has been imported, select the JAPEARSample project. Right-click to display the context menu and select [Properties]. Select [Java EE Module Dependencies] from the Properties dialog box. Select JPAClientSample and add the client to the EAR.

6-1) Creating the Dynamic Web Project

Create a dynamic Web project as a client. Since this can be completed by importing a sample, details are omitted. Refer to the following setup items.

Setup items

Setup content

Project name

JPAClientSample

Target Runtime

Interstage Application Server V11.1 IJServer Cluster (Java EE)

Configuration

Default Configuration for Interstage Application Server V11.1 IJServer Cluster (Java EE)

Add project to an EAR

Select

EAR Project name

JPAEARSample

6-2) Setting the Build Path

Set the build path (classpath) used to reference the Entity class (CountryData) and the logic class (PopulationRanking). This is already set in the imported sample project.
To check the settings, select the created project (JPAClientSample), and right-click. Select [Properties] from the context menu. Select [Java EE Module Dependencies] from the Properties dialog box to display the [Java EE Modules] tab.

Check that the following setting is selected.

Setup item

Setup content

JAR/Module

JPASample.jar

6-3) Creating the Servlet Class

Create the servlet class. The servlet class is already created in the imported sample project with the following setup items.

Setup items

Setup content

Java package

sample

Class name

ServletController

Superclass

javax.servlet.http.HttpServlet

Which method stubs would you like to create?

Constructors from superclass
Inherited abstract methods
doPost (remove the doGet check)

6-4) Specifying the Dependency Injection

The implementation for invoking the logic class is performed in the servlet class. This is already implemented in the servlet source of the imported sample project.
To create the PopulationRanking class, javax.persistence.EntityManagerFactory is required in the constructor. Create the EntityManagerFactory fields, then set the PersistenceUnit annotation and specify the Dependency Injection as shown below.

PersistenceUnit Annotation Definition

@PersistenceUnit
private EntityManagerFactory emf;

Point

Instead of the lookup method used up to J2EE1.4, Dependency Injection is used in Java EE and can be used to fetch and use an object. (During execution, the object is automatically set in a field by means of a Java EE container.)

6-5) Implementing the Server Class

Create a logic class instance like the one shown below and invoke the method. This is already implemented in the servlet source of the imported project.

Entity Invocation Method Definition

PopulationRanking ranking = new PopulationRanking(emf);
CountryData country = ranking.getCountryData(rank);

The implemented servlet class is as shown below. (The imported project servlet source is in this format).
The parts in red are the added definitions.

Servlet Class (ServletController.java)

package sample;

import java.io.IOException;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 

/**
 * Servlet implementation class ServletController
 */
public class ServletController extends javax.servlet.http.HttpServlet {

    private static final long serialVersionUID = 1L;

    //@PersistenceUnit
    @PersistenceUnit
    private EntityManagerFactory emf;

   /**
    * @see HttpServlet#HttpServlet()
    */
    public ServletController() {
        super();
        // TODO Auto-generated constructor stub
    }

   /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("ISO-8859-1");
        ServletContext sc = getServletContext();

        // Get the type of file to be invoked.
        String mode = request.getParameter("mode");
        if (mode != null && mode.equals("top")) {
            // Invoke the Input page HTML file.
            RequestDispatcher inRd = getServletContext().getRequestDispatcher("/default.jsp");
            inRd.forward(request, response);
            return;
        }

        int rank;

        // Input check
        try{
            rank = Integer.parseInt(request.getParameter("rank"));
        } catch (NumberFormatException e){
            RequestDispatcher errRd = sc.getRequestDispatcher("/error.jsp");
            errRd.forward(request, response);
            return;
        }

        PopulationRanking ranking = new PopulationRanking(emf);
        CountryData country = ranking.getCountryData(rank);

        // Check the obtained value.
        if(country == null){
            RequestDispatcher errRd = sc.getRequestDispatcher("/error.jsp");
            errRd.forward(request, response);
            return;
        }

        sc.setAttribute("ranking", country);

        RequestDispatcher outRd = sc.getRequestDispatcher("/result.jsp");
        outRd.forward(request, response);
    }
}

Point

After the required implementation is coded, right-click on the Java editor, then select [Source] > [Organize Imports] from the context menu. The import statement that is appropriate for the classpath that was set in the project can then be inserted.

6-6) Creating the I/O Page

Create the I/O page JSP. A file like the following is already created in the imported sample project.

Input Page (default.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>World ranking for total population</title>
</head>
<body>
<h1>Input page</h1>
<p> Enter a ranking from 1 to 10. </p>
<p></p>
<form action="ServletController" method="post">
    Rank :<br>
    <input name="rank" type="text" size="10">Rank<br>
    <p></p>
    <input type="submit" value="OK">
    <input type="reset" value="Clear">
</form>

</body>
</html>

Output Page (result.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>World ranking for total population</title>
</head>
<body>
<h1>Output page</h1>

Total population ranking ${param.rank}rank is "${applicationScope.ranking.countryName}"<br>
Total population is ${applicationScope.ranking.totalPopulation} people.
<br>
<hr>
<form action="ServletController" method="post">
    <input type="submit" value="Back to input page">
    <input type="hidden" name="mode" value="top">
</form>

</body>
</html>

Error Page (error.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>World ranking for total population</title>
</head>
<body>

<h1>Error page</h1>
The entered ranking is not in the specified range, or a server error occurred. <br>
<br>
<hr>
<form action="ServletController" method="post">
    <input type="submit" value="Back to input page">
    <input type="hidden" name="mode" value="top">
</form>

</body>
</html>

7) Setting the Interstage Application Server JDBC

From the Interstage Java EE Admin Console, set the JDBC so that the Oracle database can be used from the Java EE container.

Check separate documentation concerning how to use the Java EE execution environment of Interstage Application Server for details of how to launch and use the Interstage Java EE Admin Console.

7-1) Creating the JDBC Console Pool

Create an Oracle JDBC Connection Pool. Select [Resources] > [JDBC] > [Connection Pools] from the left frame to display the [Connection Pools] page.

Click [New...], then enter the following setup items.

Setup items

Setup content

Name

OraclePool

Resource Type

javax.sql.ConnectionPoolDataSource

Database Vender

Blank

Set the information, then click [Next].

Enter the following setup item in the next page.

Setup item

Setup content

Datasource Classname

oracle.jdbc.pool.OracleConnectionPoolDataSource

Add properties in the last line at [Additional Properties]. To add the properties, click [Add Property]. When input of the following setup items is finished, click [Finish].

Setup items

Setup content

User

Specify the User ID used to access the database.

Password

Specify the password that corresponds to the user name.

PortNumber

1521

networkProtocol

tcp

DatabaseName

COUNTRYDATA

serverName

myhost

DriverType

thin

7-2) Creating the JDBC Resource

Create the JDBC Resource that corresponds to the created JDBC Console Pool. From the left frame, select, [Resources] > [JDBC] > [JDBC Resource] to display the [JDBC Resources] page. Click [New] to display the [New JDBC Resource] page.

Enter the following setup items.

Setup items

Setup content

JNDI Name

jdbc/Oracle

Pool Name

OraclePool

Targets(Selected Targets)

MyDebugJEE

7-3) Setting the JDBC Deriver Classpath

Set the Oracle JDBC driver in the classpath. From the left frame, select [Configurations] > [MyDebugJEE-config] > [JVM Settings] to display the [JVM General Settings] page. Click the [Path Settings] tab and enter the following settings.

Enter the following setup items.

Setup items

Setup content

Server Classpath

<JDBC driver storage destination directory>\ojdbc6.jar

Native Library Path Suffix

<JDBC driver storage destination directory>

8) Checking Application Operation

8-1) Associating the Project with a Server

Select a server in the Servers view, then select [Add and Remove Projects] from the context menu.
Select the created EAR project from the usable projects, then click [Add]. Check that the EAR project has been added to the configured projects.

Check the following setup item, then click [Finish].

Setup item

Setup content

Configured projects

JPAEARSample

Point

If the deployment destination server in the Servers view is not registered, then it must be added. For details on how to do that, refer to "6.2.6 Checking Application Behavior".

8-2) Setting Breakpoints

Set a breakpoint at the first line of the getCountryData() method of the logic class. To set or delete a breakpoint, double-click the ruler part on the left edge of the editor.

8-3) Launching the Server

Select a server in the Servers view, then select [Debug] from the context menu.

Point

If you want to simply launch the application without using the debugger, select [Start] from the context menu.

The EAR file is deployed automatically before the server starts.

Check the following information in the Servers view:

Item to check

Contents to check

Server state

Started

Server status

Synchronized

EAR file (JPAEARSample) state

Synchronized

State of the JAR file (JPASample) under the EAR file

Synchronized

State of the WAR file (JPAClientSample) under the EAR file

Synchronized

8-4) Executing the Application

In the Servers view, select the deploying Web project (JPAClientSample), then from the context menu, select [Web browser]. The Web browser is started, and the input window is opened.

Setup item

Setup content

URL of input page

http://localhost/JPAClientSample/

Enter a population ranking in the [Rank] input field, then click [OK].

Point

The user can select the project, then select [Run As] > [Run on Server] or [Debug As] > [Debug on Server] from the context menu to add the server, add the project, launch the server, and launch the client all together.
In addition, the Web browser used as the client can be changed by selecting [Window] > [Web Browser] from the menu.

8-5) Debugging the Application

The applications runs and is interrupted at the breakpoints. Check the Variables view display. Select [Run] > [Step Over] from the menu and check the program state in the Variables view. For details, refer to "6.2.6.1 Debugging" for debugging details.

Point

In addition to checking values, values can be changed in the Variables view.

Processing that has been interrupted by the debugger can be restarted by selecting [Run] > [Resume] from the menu. This allows the processing on the server side to complete so that the output page is displayed on the Web browser. Check that the country name and total population for the entered ranking is displayed.

9) Distributing the Application to the Operating Environment

An EAR file must be created in order to distribute the application to the operating environment. The created EAR file uses the server distribution function to distribute the application to the server.

9-1) Exporting the Application

The EAR file is created from the Export wizard. To launch the Export wizard, select [File] > [Export]. From [Export] wizard, select [Java EE] > [EAR file].

The EAR file Export wizard is displayed.

Check and enter the following setup items. After the following information is set, click [Finish].

Setup items

Setup content

EAR project

Specify the enterprise application project.

Destination

Specify the creation destination for the EAR file.

9-2) Deploying to the Operating Environment

The application can be deployed from a remote environment to the operating environment by logging in to the Interstage Java EE Admin Console at the operating environment and by specifying a local EAR file.