Angular JS Magazine

marți, 13 ianuarie 2015

Reading Data From a Servlet Via Angular JS $http.get

In this tip you can see how to read data from a Servlet using $http.get. First, a simple servlet that returns a JSON string and belongs to the application named, AngularGET:

@WebServlet(name = "AtpPlayers", urlPatterns = {"/AtpPlayers"})
public class AtpPlayers extends HttpServlet {
 ...
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

  response.setContentType("application/json;charset=UTF-8");
 try (PrintWriter out = response.getWriter()) {

        out.println("[{\"name\": \"Nadal, Rafael (ESP)\", \"email\": \"nadalrafael@gmail.com\", \"rank\": \"1\"},"
                        + "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"djokovicnovak@gmail.com\", \"rank\": \"2\"},"
                        + "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"federerroger@gmail.com\", \"rank\": \"3\"},"
                        + "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"wawrinkastan@gmail.com\", \"rank\": \"4\"},"
                        + "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"ferrerdavid@gmail.com\", \"rank\": \"5\"}]");
        }
    }
 ...
}

Now, a simple Angular page that communicate with this servlet:

<!DOCTYPE html>
<html>
    <head>    
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>      
    </head>
    <body ng-app="ATP_PLAYERS">  
        <div ng-controller="atpController">
            <h5>Loading ATP players from a Servlet</h5>
            <table>
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Name</th>
                        <th>E-mail</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in atp">
                        <td>{{item.rank}}</td>            
                        <td>{{item.name}}</td>
                        <td>{{item.email}}</td>
                    </tr>
                </tbody>
            </table>
        </div>    
     
        <script language="javascript" type="text/javascript">
          angular.module('ATP_PLAYERS', [])
           .controller('atpController', function ($scope, $http) {
              $http.get('/AngularGET/AtpPlayers').success(function (data, status, headers, config) {
                $scope.atp = data;
             });
         });
        </script>
    </body>
</html>