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 {

 try (PrintWriter out = response.getWriter()) {

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

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

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      
        <script src=""></script>      
    <body ng-app="ATP_PLAYERS">  
        <div ng-controller="atpController">
            <h5>Loading ATP players from a Servlet</h5>
                    <tr ng-repeat="item in atp">
        <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;