How to read data from server using AngularJS HTTP Get method.

 AngularJS HTTP

AngularJs HTTP is a service($http) used to communicate with the server.

In this tutorial, I am going to show you :

  • Convert servlet data into JSON format.
  • How to read JSON file data from the server using agularJs HTTP Get method.

 Convert servlet data into JSON format.

user.java

package mypack;

public class user {
    private String name;
     String email;
    private String pass;

    public user(String name, String email, String pass) {
        this.name = name;
        this.email = email;
        this.pass = pass;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }
    
}

Create a Servlet

Main.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException, JSONException 
{
       response.setContentType("text/html;charset=UTF-8");
       try (PrintWriter out = response.getWriter()) 
{
           /* TODO output your page here. You may use following sample code. */
              
           String name = "demo Data";
           String email = "demo@gmail.com";
           String pass = "demo_Data";
          response.setContentType("application/json"); 
           user u = new user(name,email,pass);
           JSONObject obj = new JSONObject();
           obj.put("serverOb", u);
          
          String json = new Gson().toJson(obj);
          
          response.getWriter().write(json);
   
   
       }
   }

 

Now we have data in JSON format on the server, now create an HTML file for view data.

index.html

<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example with mysql</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var app = angular.module('myApp', []);
      app.controller('myCtrl', function ($scope, $http){
        $http({
            method : 'GET',
            url : 'Main'
            
        }).then(function mySucc(response){
            $scope.myData = response.data.map;
            $scope.statuscode = response.status;
        });
      });
    </script>
  </head>
  <body ng-controller="myCtrl">
    <table>
      <tr ng-repeat="x in myData">
        <td>{{x.name+ " "+x.email+ " "+x.pass}}</td>
      </tr>
    </table>
  </body>
</html>

 

 

 

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

19 + five =