26
Author: David D, Research Scientist [email protected] 1 Java Web Development 1) - Use JSP, like PHP, for Dynamic Web Application. Code implementation is included. 2) JSP - Model 1 Architecture: JSP for the View + Java Bean as the Model, which is the Business Logic, Database Access, Data. Code implementation is included. 3) JSP - Model 2 Architecture JSP for the View + Java Bean as the Model + Servlet as the Controller 4) JAVA in Enterprise Java for larger scale development - Modern Enterprise Java Cloud & Framework - JavaEE / J2EE Few notes: Research Scientists (R&D), our job is to do research in order to help improve things for better, benefits for every one, good for innovation, good for businesses, good for society, open and advanced. When building web application, you choose JAVA vs. Non Java, scripting Technologies. A lot of developers use non-JAVA Technologies because JAVA is complexity. But the price you pay for its power, robust, solid, and its ability to build complex application. This is a Roadmap for Java Web & Enterprise Application Development. Businesses, Investors, HR, Developers, Bosses, Managers understand Web Development in order to make right decision for your business, not depend on others. A CEO said :" - This is hard skill. If we get wrong people to build product, web application. Then it costs business, waste Time & Money to re-build, re-design. Then we get help from developers in other countries here. As a result, we lost business to competitors, lost competitiveness, lost comparativeness. Let's Build software, website for the next 20 years. "

Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

  • Upload
    others

  • View
    33

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

1

Java Web Development 1) - Use JSP, like PHP, for Dynamic Web Application. Code

implementation is included.

2) JSP - Model 1 Architecture:

JSP for the View + Java Bean as the Model, which is the Business

Logic, Database Access, Data. Code implementation is included.

3) JSP - Model 2 Architecture

JSP for the View + Java Bean as the Model

+ Servlet as the Controller

4) JAVA in Enterprise Java for larger scale development

- Modern Enterprise Java Cloud & Framework

- JavaEE / J2EE

Few notes: Research Scientists (R&D), our job is to do research in order to help improve things for better,

benefits for every one, good for innovation, good for businesses, good for society, open and advanced.

When building web application, you choose JAVA vs. Non Java, scripting Technologies.

A lot of developers use non-JAVA Technologies because JAVA is complexity. But the price you pay for its power,

robust, solid, and its ability to build complex application.

This is a Roadmap for Java Web & Enterprise Application Development. Businesses, Investors, HR, Developers,

Bosses, Managers understand Web Development in order to make right decision for your business, not depend on

others.

A CEO said :" - This is hard skill. If we get wrong people to build product, web application. Then it costs business,

waste Time & Money to re-build, re-design. Then we get help from developers in other countries here. As a result, we

lost business to competitors, lost competitiveness, lost comparativeness. Let's Build software, website for the next

20 years. "

Page 2: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

2

Stand alone JSP connect to database

JSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages.

JSP pages need to be processed on a web server like Tomcat before being sent to the client’s browser.

JSP page is translated into Java servlet before being executed. JSP technology is convenient way to code the Servlet.

Client Architecture Web Application - JSP ( Java Server Page ) alone.

JSP stand alone = PHP. Both is scripting language. JAVA is not scripting language. JAVA is Object Oriented

Programming. PHP is not JAVA, thus can't use Java Object Oriented. JSP can use Java Object.

Dynamic Web Application - All web applications, such as, PHP, JSP ... had Client (Web Browser), Application Server ( Tomcat, Apache, Web

Spere ... ), and Database Server ( MySql, Oracle, Ms Sql Server ..). AWS ( Amazon Web Services host used Tomcat ).

- In Client-Tier Architecture has no Funtional Logics or the Business Logics Tier. This Tier or Layer is responsible for:

Process commands, makes business rules, do calculations, connect database, and process data.

- Client-Tier Architecture is not MVC Architecture because no Model - View - Controller. Client-Tier has no

separation between User Interface, Presentation, or the View, and Functonal Logic, Data Access or the Model, and

no Controller.

This Client Architecture first used by PHP web scripting language, when no Cloud Computing. PHP was created in

1994 by Rasmus Lerdorf. JSP was created later by Sun Microsystems in 1998.

For web developers see JAVA difficulty, PHP is an alternative solution for their web development.

How stand-alone JSP Dynamic Web Application Works? Users open web browser, request JSP pages, such as, click on Login link or type: www.company.com/login.jsp, or

type: www.company.com/login, if the website mapped login.jsp into /login.

This login request is sent to Web Server. Then JSP, executed by web server, connect to database, get data,

manupulate data, calculate data.. Then sent HTTP response with data embedded in JSP webpage, back to users.

Just stand alone, JSP is a scripting language like PHP. It has extension jsp, such as, login.jsp like login.php.

JSP stand-lone works, executes, design web application just like PHP. But, JSP combined with other Technologies like

Page 3: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

3

Java Bean or Java Class, Java Servlet, Enterprise Java, JSP will become a very powerful technology for

web application and enterprise web app that no one can compare.

See example code How-to Implement this Architecture provided below.

MVC Architecture.

MVC 3-Tier Architecture is about the separation between the GUI, Presentation, or

the View, and the Model = all about data , or the Business Logics,

Database Data Access ... The Controller receives input, HTTP request, and

manage, handle, direct inputs to the model, or the view for manipulate, execute, or

display. It acts like Head Office dispatcher traffic control, direct & manage congested traffics of user's inputs, requests to flow better. MVC Architecture made easy, not spaghetti code, and clear development for Enterprise Application Development, because its separation of concern between tier.

Modern Enterprise Java by design is for MVC. But you need to know How-to design, architect, and write code to make MVC work. Building few small scale website projects doesn't help, and see big differences. We write code, build large scale Cloud Enterprise Application, Cloud E-commerce Application, Cloud Database Application, Cloud POS Application, large scale E-Business Apps, larger scale powerful Business Website Application. => Then integrate all software All-in-One system so we can see differences.

MVC is no spaghetti design

MVC Benefits To design MVC, use Modern Enterprise Java. By design, Modern Enterprise Java is MVC, but

know How. Having MVC is better than no architecture, spaghetti.

- Separation of concerns between Developers:

Benefits for web development because different developer has different roles, such as, Front-end web developers,

like Web Content /Graphic Design, GUI/ Screen Web Designer, just focus on the design of the View. And the back-

end developers, Java Software Developers, database Developers, just focus on the Model, which is about data,

database development.

- Separation of concerns between Roles:

Benefits for making web application robust, solid, fast, resource efficiency, high performing, security ... For example,

- The View or web browser just focus on displaying/ rendering Data. Thus make Client or web browser thin

Client, fast like static Html page. No heavy lifting connect/ access database for the View.

- The Model: just focus on the Business Logics, the Data & Database, Model data. Such as, Get/ Save/ Update/

Insert Data. Retrieve Data, Manipulate data ... All about Data.

- The Controller: just focus on manage users request, user input, URL matching.., such as, when user click on

Login or user type www.compan.com/login... It acts like Head Office dispatch traffics controller. It directs &

manages congested traffics of user's request at website to flow better.

- Separation of concerns = Clear web development. We know which role to focus the web development.

Page 4: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

4

- Easy support multi devices, since the View contains only data, just for display/ render data.

NOTE: JSP stand alone or Client Architecture doesn't have MVC. The Client or web browser does all tasks, all roles.

The Client is = the View, the Model, and the Controller. No separation of concerns. It is like one person who does

every task. Put too much pressure on the Client ( the web browser )

JSP + Java Bean - Model 1 Architecture JSP page calls a Bean component such as a JavaBean, and the bean will directly or indirectly access the database,

generally through JDBC. Data result embedded in JSP page, sent back to users.

The Bean or Java Bean is just a Java Class or Java Object, such as, login.java after compiled is login.class.

Java Bean class ( login.class) stored on Application Server like Tomcat in folder /WEB-INF/classes.

Java Bean is used for Business Logic, for access database, process data in

database, for all about data, model data ... In MVC Architecture ( Model View

Control) , Java Bean is the Model.

Model 1 Architecture = the Model ( the Bean ), the View ( JSP ). No Controller.

In this 2-Tier Architecture, Java Bean ( the Model ) is used for Business Logic, for connect, access to database...

The Bean is embedded to call in JSP page. There is no need to instance or create new object for Java Bean.

The Bean get data, process data, model data, then sent the result of data back in JSP page for presentation ( the

View ). In this Web Application 2-Tier Architecture has no Controller.

When PHP created in 1994, more than 22 years ago. JSP. Sun Microsystems created JSP, Servlet in 1998, 18 years

ago. Recently, Enterprise Java and 3-Tier Architecture, MVC is popular for Enterprise Solution.

See example code How-to Implement this Model 1 Architecture provided below.

JSP + Java Bean + Servlet - Model 2 Architecture

Model-View-Control of MVC Software Architect is popular, adapted by Software Developers to build their software

Page 5: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

5

application. So JSP, Java Bean, Servlet is used for MVC Architecture, if don't use Enterprise Java. In this old Model-

View-Controller MVC Architecture:

JSP page for the View is used for web page content, or presentation.

When access to database, the View or JSP pages call a component such as a JavaBean.

JSP page then display data, render data ...

The Java Bean for the Model, all about Data is used for implement Business Logic, Access Database, all

about Data. The bean, or Java Bean will directly or indirectly access the database, generally through JDBC ( Java

Database Connectivity ). The Bean is embedded in JSP page called as Bean component.

Servlet as Controller -> Must know How to program Servlet as Controller MVC, and for Do

Get / Post submit form. Or else Servlet is used for just Do Get / Do Post for submit form.

Thus it does not acts as Controller, not Model 2 Architecture.

- Users send request to Servlet, such as, http://www.mywebapp.com/login or click on the link Login

- The Controller or Servlet then call and instantiate a Java Bean, the Model. Such as, run the Login Bean (

LoginBean.java ) component in order to verify user ID & Password. The Java Beans connect, access to database.

- Then the Servlet Controller communicate back & forth the Model Java Bean (Java Object Oriented) in order to get

the result of data. Data then send to the View JSP page. Data can also embedded in the Bean Java Object, and

display/ render in the View JSP page. - Finally, the Result sent back to the User for View.

- Model 2 Architecture. JSP (View) + Servlet (Controller) + Java Bean (Model).

- Servlet is used and acts as Controller, not just acts as Do Get / Do Pos for submit form .

JSP + JAVA BEAN + SERVLET Model 2 Architecture is very much

a small scale Web Application NOT large scale Enterprise Web

Application.

Page 6: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

6

Not including Java Bean Objects, Servlet, Enterprise Java .. just JSP alone is as

powerful as PHP. You can develop your Web Application in both PHP & JAVA,

host them in same Application Server like Tomcat, use same Database Server.

However, for Cloud Computing Web Application, Software as a Service ( SaaS),

it must design & develop using Enterprise Java for large scale software

development. For example, a SaaS that includes many software components,

such as, Database Application, E-commerce, Office Business Application ...

Now, Let's implement

JSP + JDBC Connect to database as stand alone

The code: connect_db.jsp

It is used to access database as stand alone.

It connects database -> Open database salesx -> Read table employees -> Display result of data in JSP page.

To display data, we can use out.print, a JSP API, or we can display used HTML Table.

/* Author: David Dang

-This program shows how to implement stand-alone JSP Web Application.

-JSP page can be mapped into servlet url, for example, www.company.com/login.jsp is mapped as: www.compan.com/login

- Output: we used 2 different ways to display output: 1) Use out.print, a method API of JSP. Or, 2) Use HTML table.

*/

<%@ page language="java" import="java.sql.*" %>

<html>

<head>

<title> Employee Data </title>

</head>

<body bgcolor="white">

<%

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

final String db_url ="jdbc:postgresql://localhost:5432/salesx";

final String user = "salesxu";

final String password = "salesxu1";

try {

Page 7: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

7

Class.forName("org.postgresql.Driver");

conn = DriverManager.getConnection ( db_url, user, password );

} catch (ClassNotFoundException e) {

out.println("<h2>Driver not found:" + e + e.getMessage() + "</h2>" );

}catch (SQLException e) {

System.out.println(e);

}

try {

stmt = conn.createStatement();

rs = stmt.executeQuery( "SELECT eid, fname, lname, phone, address, age FROM employees order by eid ASC; ");

out.println( "<table border=1>" );

out.println("<TR> <TH>ID</TH><TH>Fname</TH> <TH>Lnam</TH> <TH>Phone</TH> <TH>Address</TH>

<TH>Age</TH></TR>");

while ( rs.next() ) {

int eid = rs.getInt ("eid");

String fname = rs.getString("fname");

String lname = rs.getString("lname");

String phone = rs.getString("phone");

String address = rs.getString("address");

int age = rs.getInt("age");

out.println("<tr><td>"+eid + "</td>" +

"<td>"+fname+ "</td>" +

"<td>"+lname+ "</td>" +

"<td>"+phone+ "</td>" +

"<td>"+address+ "</td>" +

"<td>"+age+ "</td>" +

"</td></tr>" );

}

out.println( "</table>" );

out.println("==== Display data used HTML Table ====") ;

%>

<BR>

<TABLE BORDER="1">

<TR> <TH>ID</TH> <TH>Fname</TH> <TH>Lnam</TH> <TH>Phone</TH> <TH>Address</TH>

<TH>Age</TH>

</TR>

<%

rs.close();

rs = stmt.executeQuery("SELECT eid, fname, lname, phone, address, age FROM employees order by eid ASC; ");

while( rs.next() ) { %>

<TR>

<TD> <%= rs.getInt(1) %></td>

<TD> <%= rs.getString(2) %></TD>

Page 8: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

8

<TD> <%= rs.getString(3) %></TD>

<TD> <%= rs.getString(4) %></TD>

<TD> <%= rs.getString(5) %></TD>

<TD> <%= rs.getInt(6) %></TD>

</TR>

<% } %>

</TABLE>

<%

} catch (SQLException e) {

out.println( "<h1>exception: "+ e + e.getMessage() + "</h1>" );

}

finally {

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se){

se.printStackTrace();

}

try{

if(rs!=null)

rs.close();

}catch(SQLException se1){

se1.printStackTrace();

}

try{

if(conn!=null)

conn.close();

}catch(SQLException se2){

se2.printStackTrace();

}

}//

%>

</body>

</html>

ID Fname Lnam Phone Address Age

1 Peter Ng 905-322-8821 218 Street 21

2 hello ng 123 123 street 35

3 Paul Smith 905-322-8833 318 Street 22

4 Helen G 905-322-8821 218 Street 21

9 Lee L 905-215-3280 216 String 29

14 Tina P 905-215-3280 215 String 29

Page 9: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

9

Example of PHP code: Connect / Access to database You notice PHP same as JSP. Name of PHP file extension is php, such as, connect.php

connect_db.php = Connect to database --------------------------------------------

<html>

<head>

<title>First PHP Page</title>

</head>

<body>

<h1><?php echo “Create table database use PHP tag in HTML. ”; ?></h1>

<?php

$host = "host=127.0.0.1";

$port = "port=5432";

$dbname = "dbname=employeedb";

$source = "user=postgres password=emp345";

$db = pg_connect( "$host $port $dbname $source" );

if(!$db){

echo "Error : Can't open database\n";

} else {

echo "Opened successfully\n";

}

?>

</body>

</html>

create_db.php = Create A Database Table -------------------------------------------

<html>

<head>

<title>First PHP Page</title>

</head>

<body>

<h1><?php echo “Create table database use PHP tag in HTML. ”; ?></h1>

<?php

$host = "host=127.0.0.1";

$port = "port=5432";

$dbname = "dbname=employeedb";

$source = "user=postgres password=pass345";

$dbcon = pg_connect ( "$host $port $dbname $source" );

Page 10: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

10

if(!$dbcon){

echo "Error : Unable to open database\n";

} else {

echo "Opened database successfully\n";

}

// $sql = "The point of the \"argument" was to illustrate the use of here documents";

//$sql = <<<EOF The point of the "argument" was to illustrate the use of here documents EOF;

$sql =<<<EOF

CREATE TABLE EMPLOYEE

(EID INT PRIMARY KEY NOT NULL AUTO_INCREMENT,

NAME TEXT NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR(250),

SALARY REAL);

EOF;

$ret = pg_query ($db, $sql);

if(!$ret){

echo pg_last_error ($db);

} else {

echo "Table created successfully\n";

}

pg_close ($dbcon);

?>

</body>

</html>

insert.php = Insert Data in Table

-------------------------------------------- <html>

<head>

<title>First PHP Page</title>

</head>

<body>

<h1><?php echo “Insert data in database use PHP tag in HTML. ”; ?></h1> <?php

$host = "host=127.0.0.1";

$port = "port=5432";

$dbname = "dbname=employeedb";

$source = "user=postgres password=emp123";

$dbcon = pg_connect( "$host $port $dbname $source " );

Page 11: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

11

if(!$dbcon){

echo "Error : Unable to open database\n";

} else {

echo "Opened database successfully\n";

}

$sql =<<<EOF

INSERT INTO EMPLOYEE (EID,NAME,AGE,ADDRESS,SALARY)

VALUES (1, 'Paul', 32, 'California', 20000.00 );

INSERT INTO COMPANY (EID,NAME,AGE,ADDRESS,SALARY)

VALUES (2, 'Allen', 25, 'Texas', 15000.00 );

INSERT INTO COMPANY (EID,NAME,AGE,ADDRESS,SALARY)

VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );

INSERT INTO COMPANY (EID,NAME,AGE,ADDRESS,SALARY)

VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );

EOF;

$ret = pg_query($db, $sql);

if(!$ret){

echo pg_last_error($db);

} else {

echo "Records inserted successfully\n";

}

pg_close($db);

?>

</body>

</html>

select_db.php = SELECT Data from Table

------------------------------------------

<html>

<head>

<title>First PHP Page</title>

</head>

<body>

<h1><?php echo “Select data from database use PHP tag in HTML. And display data in HTML page.”; ?></h1>

<?php

$host = "host=127.0.0.1";

$port = "port=5432";

$dbname = "dbname=employeedb";

$source = "user=postgres password=emp123";

Page 12: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

12

$dbcon = pg_connect( "$host $port $dbname $source" );

if(!$dbcon){

echo "Error : Unable to open database\n";

} else {

echo "Opened database successfully\n";

}

$sql =<<<EOF

SELECT * from EMPLOYEE;

EOF;

$ret = pg_query($db, $sql);

if(!$ret){

echo pg_last_error($db);

exit;

}

while($row = pg_fetch_row($ret)) {

echo "ID = ". $row[0] . "\n";

echo "NAME = ". $row[1] ."\n";

echo "ADDRESS = ". $row[2] ."\n";

echo "SALARY = ".$row[4] ."\n\n";

}

echo "Select done successfully\n";

pg_close($db);

?>

</body>

</html>

JSP + Java Bean. Model 1 Architecture. JSP page also call a bean component such as a JavaBean, and the bean will directly or indirectly access the database,

generally through JDBC.

Separation of Business Logic from Page Presentation -- Calling JavaBeans

We use Java Bean or Java Object to define business logic. In MVC Architecture, it is called Model.

JavaBeans is embedded in JSP page, that are invoked from the JSP page.

Java Bean or Bean is just a Java Class.

After compiled, it is a Java Class, such as, Admin.java -> Admin.class

In Application Server like Tomcat, Bean Class is stored in: /WEB-INF/classes or /WEB-INF/classes/db

JSP is stored in folder /ROOT/*jsp or /ROOT/app/*.jsp

Page 13: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

13

The following syntax for defining and creating an instance of a JavaBeans class embedding

JSP page:

<jsp:useBean id="objectBean" scope="session" class="package.NameBeanClass" />

Later in JSP page, you can use this bean instance, as in the following example:

Tax of amount is: <%= objectBean.calTaxTotal(1000.0) %>

The separation of Business Logic ( the Model) and JSP page presentation ( the

View ) allows developers divide the responsibilities between the Java / back-

end Programmer who is responsible for writing code Java Bean for the business

logic, and for Database, Data, and the front-end developer who is responsible

for the dynamic content of webpage, JSP page.

Use Java Bean for Business Logic, for Database Access, Connectivity.

In this example, we will use Java Bean, a Java file named: connect.java is used to connect to database.

package db;

/* connect.java - a Java Bean */

/* Author: David Dang

This program shows how to implement Java Bean or Java Class in Web Application.

Java Bean or Java Class is used for the Implementation of Business Logics, or the Model in MVC (Model-View-Control)

Architecture. */

package db;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

Page 14: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

14

import java.sql.SQLException;

import java.sql.Statement;

public class connect {

static final String USER = "salesxu";

static final String PASS = "salesxu1";

static final String DB_URL = "jdbc:postgresql://localhost:5432/salesx";

Connection conn = null;

PreparedStatement pstmt = null;

Statement stmt = null;

ResultSet rs = null;

public void connect_db() {

try {

Class.forName("org.postgresql.Driver");

conn = DriverManager.getConnection ( DB_URL, USER, PASS );

} catch (ClassNotFoundException e) {

System.out.println("<h1>Driver not found:" + e + e.getMessage() + "</h1>" );

}catch (SQLException e) {

System.out.println(e);

}

}

public ResultSet processData (String sql) {

try {

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

return rs;

}

catch (SQLException e) {

System.out.println( "<h1>exception: "+ e + e.getMessage()+"</h1>" );

}

return null;

}

public void disconnect_db ( ResultSet rs ) {

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se){

se.printStackTrace();

}

try{

if(rs!=null)

rs.close();

}catch(SQLException se1){

se1.printStackTrace();

}

try{

if(conn!=null)

Page 15: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

15

conn.close();

}catch(SQLException se2){

se2.printStackTrace();

}

}

public void disconnect_db () {

try{

if(pstmt!=null)

pstmt.close();

}catch(SQLException se){

se.printStackTrace();

}

try{

if(conn!=null)

conn.close();

}catch(SQLException se2){

se2.printStackTrace();

}

}

public String displayMsg(String msg) {

return msg ;

}

public double calculateInterest(double loan, double rate, int years)

{

double interest = years * (rate * loan/100);

return interest;

}

public int deleteRecord (int id) {

String sql ="DELETE from employees where eid =? ";

try {

pstmt = conn.prepareStatement (sql);

pstmt.setInt(1, id);

int rows = pstmt.executeUpdate ();

return rows;

} catch (SQLException e) {

e.printStackTrace ();

}

return 0;

}

}

Connect_bean.jsp - A JSP page call Java Bean connect.java in order to connect, access to database.

/*

Author: David Dang

This program shows how to implement Java Bean or Java Class in JSP Web Application.

Java Bean or Java Class is used for the Implementation of Business Logics, or the Model in MVC (Model-View-Control)

Architecture.

Page 16: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

16

*/

<%@ page language="java" import="java.sql.*"%>

<jsp:useBean id="connect" scope="session class="db.connect" />

<html>

<head>

<title> Sales </title>

</head>

<body bgcolor="white">

<%

ResultSet rs = null; // get return data in ResultSet

%>

=> Use Java Bean or Java Class to calculate Interest and display directly in JSP page in HTML mode ( not in within scriptlet

elements = <% %> ).

Interest is: <%=connect.calculateInterest(10000, 2.5, 5) %>

<%

out.println ("<BR>=> You can also display Java Bean in scriptlet elements. Interest is: " + connect.calculateInterest(10000, 2.5, 5)

) ;

out.println ("<BR>=>" + connect.displayMsg (" Use Bean connect to database. And display data in table.") ) ;

connect.connect_db(); // Connect to database use Java Bean

try {

String sql = "SELECT eid, fname, lname, phone, address, age FROM employees order by eid ASC; ";

rs = connect.processData (sql); // Process data, get return data in ResultSet use Java Bean.

out.println( "<table border=1>" ); // Now just display data.

out.println("<TR> <TH>ID</TH><TH>Fname</TH> <TH>Lnam</TH><TH>Phone</TH><TH>Address</TH>

<TH>Age</TH></TR>");

while ( rs.next() ) {

int eid = rs.getInt("eid");

String fname = rs.getString("fname");

String lname = rs.getString("lname");

String phone = rs.getString("phone");

String address = rs.getString("address");

int age = rs.getInt("age");

out.println("<tr><td>"+eid + "</td>" +

"<td>"+fname+ "</td>" +

"<td>"+lname+ "</td>" +

"<td>"+phone+ "</td>" +

"<td>"+address+ "</td>" +

"<td>"+age+ "</td>" +

"</td></tr>" );

}

out.println( "</table>" );

}

catch (Exception e) {

out.println( "<h1>exception: "+ e +e.getMessage()+"</h1>" );

}

finally{

connect.disconnect_db(rs); // Java bean disconnect from database

}

%>

Page 17: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

17

</body>

</html>

-- The Program output -----

we mapped http://localhost:8080/jsp/connect_bean.jsp into url = http://localhost:8080/jsp/connect_bean

NOTE: /jsp/ or any folder name like /app/ is ok. For example: http://localhost:8080/app/connect_bean

MVC 3-Tier Architecture - Enterprise Java:

Enterprise Java Cloud, and Enterprise JavaEE/J2EE

3-Tier MVC in Modern Enterprise Java Architecture, by design is MVC

Architecture, for Cloud Computing Web Application Development,

Software as a Service (SaaS)

Unlike JSP+JAVA BEAN + SERVLET is very much Web Application, Enterprise Java Cloud is by design is

Enterprise Java Application, large scale Java Development.

It is true MVC (Model-View-Control ) Architecture.

=> Compared to JSP + JAVA BEAN + SERVLET Web Application, this Enterprise Java Cloud is so much better,

advanced, efficient, robust, and enterprise for large scale Java Development.

Since it is better, efficient, robust, advanced, enterprise, this technology should be used to

replace the old JSP + JAVA BEAN + SERVLET Technology. Move forward to the better. Save Time & Money for Web Application, Cloud Software Development (SaaS).

Page 18: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

18

It is light, fast, robust, and efficient. Good for Cloud.

It is Enterprise large scale Java development.

Modern Enterprise Java Cloud used Framework

For handling and managing database connectivity, database resource, connection pool, access database,

process data, security, POJO, and resources more efficient, more robust, more powerful, and reduce bugs.

It built in many components, APIs, Libs that helps reduce cost of software development.

Java Bean is replace by POJO ( Plain Old Java Object ). POJO includes different Java Components, such as,

DAO ( Data Access Object ), DM ( Domain or PD ), Impl for implement Interfaces.

Enterprise Java Cloud used Dependency Injection to insert POJO.

It has its own the Controller that is built-in mechanism to know how to direct & manage traffics of

users better ( Not Servlet Controller like JSP-JAVA BEAN-SERVLET Architecture ) => But you need to

know how to setup, and program the Controller to make it work. POJO is injected in Controller. POJO access database get data, manipulate data, return data.

JSP in Enterprise Java Cloud is used for just the View. It is just like a static HTML. No access database,

no database connectivity. No Java Bean (Java Object) embedded like Model 1 Architecture.

JSTL or JSP Standard Tag Library (JSTL) is used sometimes to process data.

Data is process by POJO, then send data to JSP page for displaying data, rendering data.

Data is put in Model used: ModelMap model ;

Such as: model.put ("customer", customer); = Put POJO Customer Data Object in Model.

model.put("lstProduct", lstProduct); = Put Array List of products in model data

Then the Model of Data is returned by ModelAndView() function API by:

return new ModelAndView ("ViewCustomerInvoiceData", "model", model);

where ViewCustomerInvoiceData.jsp is just a JSP page.

JSP in Modern Enterprise Java Cloud is used just for View only. No access

database. That's why the web browser run very fast, because its job just to display/ render data.

The Model or Plain Old Java Object ( POJO like Superman ) will do the heavy

lifting jobs like connect/ access, read data in database, and all about data.

Page 19: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

19

Deployment Enterprise Java Cloud, We use dispatcher-servlet.xml, and web.xml

Deployment Descriptor

Enterprise Java Cloud by design is 3-Tier MVC Architecture or Server Side MVC

Architecture. Modern Enterprise Java Cloud & Framework makes MVC

Architecture easy implement.

- 3-Tier MVC Architecture - JSP is the View (web browser), POJO is the Model, Controller is at Server.

- It is good for Cloud, because it is light, faster than Enterprise Java JavaEE/J2EE, which is heavy duty used by

banks, big businesses for Enterprise Web Applications.

- The View or web browser in Enterprise Java Cloud is used just to display data. Thus its client is Thin Client.

That's why in the implementation of Modern Enterprise Java Architecture, you will never

see JSP, the View, embedded Java Bean, nor connect/ access to database, process data ...

JSP only embedded data for displaying / rendering data only.

- In 2-Tier Architecture, Client Architecture, the Client or web browser is called heavy client or Thick Client,

because heavy used such as access database.

Page 20: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

20

Note: When design web application, every time users connect database / access database / get data is a heavy

lifting job for web site. Because, it takes a lot of times for authentication, communicate back & forth to database

server. Then it takes a lot of resources to store data. Then you have to manage resource, such as, release resource

after dis-connection, or else your website will be exhausted of resource... Thus a lot of work, heavy lifting job.

Java Plain Old Object or POJO will hold data in its objects, thus reduce times connect/ re-connect to database get

data again when need Data. Try to avoid this heavy duty database task as much as possible. Because when your

website has tens of thousands of users doing these heavy database tasks, will put a lot of pressure on a whole your

website application. In Modern Enterprise Java Architecture, it used method called: ModelAndView() helps send

data to the View from Controller, after got data from POJO.

- Modern Enterprise Java 3-Tier Architecture: Users make request from the web browser, or the View.

The Controller handles the request, communicate back & forth with the Model that handle the connect, access to

database. The result of data is embedded in the View or web browser.

Data is displaying/ rendering in different devices.

Enterprise Java Cloud that don't use Servlet. It has its own the Controller.

Page 21: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

21

MVC 3-Tier Architecture - JavaEE / J2EE This is heavy duty Enterprise Java supported by Oracle for big businesses, financial institutions, banks to implement

Web Application with Oracle back-end. Oracle is a relational database.

Relational Database Oracle is very popular used by big businesses, big corporation. Oracle is 160 Billions company,

its Oracle database is number 1 database used in today market.

However, Relational Database Oracle is not popular among Social Media companies, like Linked IN, because data

used by social media company format more like texture ( a lot of text, message, twitter feeds, video, images.. For

example, you can't store images, photos in Relational Table. ), document data, very different with Business

data like Customer, Invoice, Order, Product ....

Only Relational Data & SQL has JOIN, very powerful feature in database for get data and JOIN them

from different data point, data source. Other databases used by Social Media DON'T HAVE JOIN, DON'T

USE DATABASE SCHEME. DON'T USE RELATIONAL TABLE.

In JavaEE / J2EE, Oracle specification, you see code like:

@OneToMany (mappedBy="customer", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity=

Order.class, fetch= FetchType.EAGER) private List<Order> orders;

This code allows map 1-to-Many between table Customer and table Orders. Prove only Relational Data used in

J2EE. Specially, Small & mid sized Businesses don't use social media data, Businesses use

Relational Data. That's why, any company use Oracle, has no choice, but use Java

language. Because Oracle built-in a lot APIs in JavaEE/ J2EE Enterprise Java in order to

make JAVA-ORACLE become a standard, a specification.

Why not build on the strong & robust foundation so that will not

redesign, revamp, rebuild -> Pickup the right technology. Build for the

next 20 years. Invest in the long term. Save Time & Money for

Software Development.

Page 22: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

22

In JavaEE/ J2EE, Servlet, JSP, Java Bean is used limited in Web Container.

In recently, Oracle release a new version of Enterprise Java JavaEE / J2EE.

1) The old J2EE deploys heavy Entity Beans for accessing database. While The new J2EE deploys Java Persistence Entity is a lightweight persistence domain object, to access data which is generalized to address issues of portability, faster, more efficient, more powerful handling & tracking & managing Cascade Parent - Child Relationship, complex Join Multi Relationship for Relational Database. - Before The new J2EE, there was no easy way to share data throughout the application. 2) In The new J2EE, Entity Bean can be effortlessly converted to DAO and vice versa. - This is not possible in The old J2EE. 3) The new J2EE has Dependency Injection. It performs better. It uses Java Object POJO. - The old J2EE does not implement POJO, and no DI. 4) The new J2EE elimination of Home interface (= Home and Object interfaces are no longer required – you need the Business Interface only) faster, lighter, more efficient. Gives simpler lookup process in The new J2EE than in The old J2EE. - The old J2EE is heavy when it comes to writing Home and Remote interfaces. 5) The new J2EE are faster than JNDI For reference of objects, deployed by The old J2EE. 6) The new J2EE simple POJO doesn’t need to execute container call back methods such as ejbActive, ejbStore .. which are used by The old J2EE. 7) The code is difference between two.

Page 23: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

23

=> It is different with Enterprise Java Cloud that don't use Servlet.

=> JavaEE/ J2EE is used for all kinds of Relational Database, not just Oracle.

- In JavaEE/ J2EE, Java Bean, JSP, Java Servlet are used in Web Component.

- This above picture is the latest J2EE / Java EE from Oracle.

Example Code JavaEE / J2EE:

import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;

persistence.xml Persistence Unit used for Configure & Register Customer class, Order class & Oracle Database connectivity. <?xml version="1.0" encoding="UTF-8"?>

Page 24: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

24

import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table import javax.persistence.OneToMany; @Entity(name = "CUSTOMER") @Table(name = "CUSTOMER") // map to table Customer @NamedQueries ({ @NamedQuery ( name = "Customer.getAllCustomer", query = "SELECT cust from Customer cust" ), @NamedQuery ( name = "Customer.deleteCustomer", query = "DELETE from Customer cust where cust.customerId = :id" ) })

public class Customer implements Serializable { // = JAVA map object Entity Customer to table Customer @Id //signifies the primary key // Primary key of CUSTOMER table @Column(name = "CUSTOMER_ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private long customerId; @Column(name = "FIRST_NAME", length = 50) private String firstName; @Column(name = "LAST_NAME", nullable = false, length = 50) private String lastName; @Column(name = "ADDRESS") private String address; @Column(name = "EMAIL") @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\." +"[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" +"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="{invalid.email}") protected String email; private String nonsenseField = ""; // more columns of CUSTOMER table define here ....

@OneToMany (mappedBy="customer", cascade =

CascadeType.ALL, orphanRemoval = true, targetEntity= Order.class, fetch= FetchType.EAGER) private List<Order> orders; @Transient public String getNonsenseField() { return nonsenseField; } public void setNonsenseField(String nonsenseField) { this.nonsenseField = nonsenseField; }

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="Entity_Relationship"> <class>entity.Customer</class> <class>entity.Order</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@//mycompany.com:1521/my_dept"; create=true /> <property name="javax.persistence.jdbc.user" value="admin3x"/> <property name="javax.persistence.jdbc.password" value="admin321"/> <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/> <property name="logging.level" value="FINE"/> <!-- should create the database schema automatically --> <property name="ddl-generation" value="create-tables"/> <property name="ddl-generation.output-mode" value="database" /> </properties> </persistence-unit> </persistence>

Example of CustomerEjbDAO.java import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class CustomerEjbDAO implements CustomerEjbDAOLocal { @PersistenceContext private EntityManager em; @Override public void addCustomer(Customer Customer) { if ( getCustomer(Customer.getCustomerId()) == null ) em.persist(Customer); }

@Override public void editCustomer(Customer customer) { em.merge(Customer); } @Override

Page 25: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

25

public long getCustomerId() { return customerId; } public void setCustomerId (long customerId) { this.customerId = customerId; } // getter and setter Order data for @OneToMany public List<Order> getOrders() { return orders; } public void setOrders (List<Order> orders) { this.orders = orders; } // ...more ... }

Example of public interface CustomerEjbDAOLocal.java import javax.ejb.Local; @Local public interface CustomerEjbDAOLocal { public void addCustomer(Customer customer); public void editCustomer(Customer customer); public void deleteCustomer( long CustomerId); public Customer getCustomer( long customerId); public List<Customer> getAllCustomers(); public void enterNewOrder (long customerId, Order newOrder); public void removeOrder(Order order); public List<Order> getOrdersById (long customerId); public void removeCustomer (long customerId); // .... more }

public void removeCustomer (long customerId) { Customer customer = em.find(Customer.class, customerId); if ( customer != null) em.remove(customer); } } @Override public void deleteCustomer (long customerId) { // Query query = em.createQuery("DELETE FROM Customer cust where cust.CustomerId = :id"); // query.setParameter("id", CustomerId).executeUpdate(); em.createNamedQuery ("Customer.deleteCustomer").setParameter("id", CustomerId).executeUpdate(); } @Override public Customer getCustomer (long customerId) { return em.find (Customer.class, customerId); } @Override public void removeCustomer (long customerId) { Customer customer = em.find(Customer.class, customerId); em.remove(customer); } @Override public List<Customer> getAllCustomers() { return em.createNamedQuery("Customer.getAllCustomer").getResultList(); } @Override public void removeOrder(Order order) { getOrders().remove(order); order.setCustomer(null); } @Override public void enterNewOrder (long customerId, Order newOrder) { Customer cust = em.find(Customer.class, customerId ); if ( cust != null ) { cust.getOrders().add(newOrder); newOrder.setCustomer(cust); } // .... more }

Summary Not including Java Bean, Servlet, Enterprise Java Cloud, JavaEE/J2EE,

just JSP alone is as powerful as PHP. Both scripting language, PHP is not JAVA.

However, for Cloud Computing Web Application, for Software as a Service

(SaaS), you should use Enterprise Java for large scale software development.

I explain different levels of Java Development from small scale to large scale:

- From JSP Client Architecture -> JSP + JAVA BEAN Model 1 Architecture -> JSP+JAVA BEAN+ SERVLET

Model 2 Architecture for Web App -> To Enterprise Java Application 3-Tier MVC.

Page 26: Java Web DevelopmentJSPs ( Java Server Page ) are, like PHP pages, server-side scripting pages. JSP pages need to be processed on a web server like Tomcat before being sent to the

Author: David D, Research Scientist [email protected]

26

- I explain 2 different of Enterprise Application: 1) Modern Enterprise Java, light, robust, large scale, good

for Cloud, and Enterprise JavaEE/ J2EE for Enterprise Business Application like Banks, mid & big sized

businesses, for business use Oracle backend.

When you build Web Application, even Model 1 Architecture JSP + Java

Bean (Java Object Oriented) is as powerful or much better than other

non-Java scripting technologies. But, should go for Enterprise Solution.

It takes us many years of R&D, hard work days & nights Product Development.

Building few small scale website projects doesn't help see big differences. We build, write

code large scale Cloud Enterprise Application, Cloud Commerce Application, Cloud Database

Application, large scale Cloud Business Website Application, large scale E-business Apps.

Thus we can see big differences in different Technologies. We had gone through R&D

different implementations, and write code from: small scale Scripting Technology JSP

stand-alone, Client Architecture -> JSP + Java Bean Model 1 Architecture -> JSP + Java Bean

+ Servlet Model 2 Architecture -> Finally, we made decision to implement ultimate large

scale Enterprise Web Application, and Enterprise Solution.

We rather move forward next 20 years than move backward 20 years.

If don't get it right in the beginning -> It is a big waste of Time & Money to re-

design, re-build. We have to move forward to the better, to the top, and the

best.

This is research paper. It helps you understand different web application

technologies, and thus make right decision, because the bosses, the managers

don't know web application. They depend on your skill, your knowledge.