How To Retrieve Oracle Database Record Using AngularJS,JSP - onlyxcodes

Monday, 7 May 2018

How To Retrieve Oracle Database Record Using AngularJS,JSP

Hi, in this tutorial post you will see codes of How to Retrieve Oracle Database Record using AngularJS & JSP.

You can not retrieve data from the database directly using AngularJS. The AngularJS reflects a front-end framework. It's enhancing client-side HTML property.

The AngularJS provides services from $http. Using this service to send your request to the Web Server page and to retrieve data from the server available. I use the JSP web page as a job server in this tutorial. This page gets the request and returns the response.

Let's dive into the tutorial where we use AngularJS to retrieve server data.

How To Retrieve Oracle Database Record Using AngularJS, JSP

Table Content

1. Make Table

2. Build Project in NetBeans

3. Make app.js [ AngularJS File ]

4. Make records.jsp [ Server File ]

5. Make index.html [ View File ]

6. Output


1. Make Table

First of all, I draw books called tabled in the SQL command prompt for oracle. Down SQL command invokes your SQL oracle command prompt after effective table making.

create table books(
book_id number(5),
book_name varchar2(20)
);

Make Table in Oracle SQL Command

I type the SQL query command in this table and insert four dumping data. Wrap up the SQL insert query command below.

insert into books(book_id,book_name)values(1,'java');
insert into books(book_id,book_name)values(2,'html');
insert into books(book_id,book_name)values(3,'css');
insert into books(book_id,book_name)values(4,'javascript');

insert four dumping data in table

2. Build Project in NeBeans

1 – Open NetBeans, go to section top and select File->New Project option.

File->New Project

2 – Look open, configure the popup window, select Java Web option on the left-hand side and select Web Application on the right-hand side, and click next.

select Java Web option on the left-hand side and select Web Application on the right-hand side,

3 – See again opening a new popup window, everything depends on you in this section that you add project name, and click to the next button.

add project name, fetch data from Oracle Database using AngularJS

4 – Finally, the last step to click the Finish button to build a project entirely, see the structure of the project directory below.

click the Finish button to build a project

Project Directory Structure of NetBeans IDE.

Project Directory Structure with NetBeans IDE

3. Make app.js [ AngularJS File ]

See creating this file separately within this file we build AngularJS codes for server fetch data.

var books=angular.module('myApp',[]);

books.controller('myController',['$scope','$http',function($scope,$http){

        $http({
            method:'GET',
            url:'http://localhost:8080/fetch_oracle_data_in_angularjs/record.jsp'
        }).success(function(data){
            $scope.rows=data;
        });
}]);

A module is a collection of services, directives, controllers, filters, and configuration information (according to AngulrJS doc.)

In AngularJS modules which specify how we will structure and bootstrap our application.

We construct an application module using angular.module() function, here the first parameter is a module name myApp. The second parameter is an empty array [ ] bracket, if you use others to insert in this bracket, AngularJS can have more dependencies.

Note:- Here, we pass an empty array [ ] because I don't have any other dependence.

This module assigns the object to books here.

Inside the books module object, we create the controller called myContoller using the function Controller().

Inside the controller function, we pass $scope and $http to two AngularJS services.

$http renders a server request (record.jsp) by providing the URL address and returns a response. I used the GET method here.

The JSON response data fetch from the remote server is the inside success () function. The response data was wrapped in the called rows array.

Note: - The scope is the binding element between the HTML (view) and the JavaScript (controller). The scope is a model.

Exactly here $scope service binds the property value of the rows array that is being retrieved from the server. That array value fetches in HTML (view) by ng-repeat directive.

See the below figure for easy comprehension of the entire structure of the codes above.

easy comprehension of AngularJS codes

4. Make record.jsp [ Server File ]

This file is a server file and is silently working on the back end side. This file handling gets a request and the response is sent in JSON format.

See below for simple codes in JSON array format syntax.

[
 {
  "book_id"  :  "1"  ,  "book_name"  :  "java"
 }
]

On this page, we set up an Oracle database connection, customizing and embedding JSP codes according to the above JSON format because of fetchable dumping data from table display in JSON format.

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>

<%
    String url="jdbc:oracle:thin:@localhost:1521:XE" ; //database url string
    String username="system"; //database username
    String password="tiger"; //database password

    try
    {
        Class.forName("oracle.jdbc.driver.OracleDriver"); //load driver
        Connection con=DriverManager.getConnection(url,username,password); //create connection
        
        PreparedStatement pstmt=null; //create statement
        
        pstmt=con.prepareStatement("select * from books"); //sql select query
        ResultSet rs=pstmt.executeQuery(); //execute query and set in ResultSet object rs.
        
        out.print("[");
        rs.next();          //fetch record "JSON" format type.
        while(true)
        { 
        %>
            {
                "book_id" : "<%=rs.getInt("book_id")%>" , "book_name" : "<%=rs.getString("book_name")%>"
            }
        <%
            if(rs.next())
            {
            %>
                ,
            <%
            }
            else break;
        }
        out.print("]");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
%> 

Note:- I use a bootstrap package in index.html(view) file and that package class code that applies to a simple HTML table because fetchable all data display in a visually good way.

5. Make index.html [ View File ]

It's either a view or a client file. First, we include AnguarJS library, bootstrap package CSS & JS library in this file and include AngularJS codes of app.js file created separately.

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.12.4-jquery.min.js"></script>
<script src="js/1.5.0-rc.0-angular.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="app.js"></script>

I put the main codes of this file.

<div ng-app="myApp" class="panel-body" ng-controller="myController">
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Book Name</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="row in rows">
                    <td>{{row.book_id}}</td>
                    <td>{{row.book_name}}</td>
                </tr>                   
            </tbody>
        </table>
    </div>            
</div>

Use the ng-app directive to designate myApp as the root element of the Angular application in the < div > tag.

The application controller myController is added to the same < div > tag using the ng-controller directive

The current value of the rows array has access inside < tr > tag which is referred by row.

Tip: -  ng-repeat expression work like a foreach loop.



6. Output

get data from database and display in table format

Download Codes

3 comments:

  1. Hey, I found your website helpful. good :)

    ReplyDelete
  2. Excellent blog, good to see someone is posting quality information. Thanks for sharing this useful information. Keep up the good work.
    Home Tutors in Delhi | Home Tuition service

    ReplyDelete