Sai Krishna Sai Krishna - 1 year ago 129
Java Question

I am trying to fetch data from a servlet into a jsp using angularjs. However, the ng-click seems to be not working. What am I doing wrong?

Please find my code below :


<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script src=""></script>
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', function($scope, $http) {
$scope.getDataFromServer = function() {
$http.get('AngularServlet',function(data) {

<div ng-app="myApp">
<div controller="MyController">
<button ng-click="getDataFromServer()">Fetch data from server</button>
<p>First Name : {{person.fname}}</p>
<p>Last Name : {{person.lname}}</p>

The Servlet code :

package com.controller;
public class AngularServlet extends HttpServlet
private static final long serialVersionUID = 1L;

public AngularServlet()

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//JSONObject obj = new JSONObject();

try {

PersonalData personData = new PersonalData();

String json = new Gson().toJson(personData);
catch (Exception e) {

PersonalData is a simple class with the getter and setter methods for fname and lname. Now when I run the angularjsp.demo on the server and click on Get Data From Server Method , nothing happens. I am not sure if the ng-click is working properly in the first place. Am I doing something wrong ?

The web.xml is :


Edit 1: I am getting the proper json output on running the servlet manually.

Answer Source

Please try it. I have tried. Doesn't seem a problem like this.

public class PersonalData {
  private String fName;
  private String lName;
//setters getters...

Try it that way.

<script type="text/javascript" src="">      </script>
 angular.module('myApp', [])
 .controller('MyController', ['$scope', '$http', function($scope, $http) {
  $scope.getDataFromServer = function() {
         $scope.person = data;

Access to the data.

<p>First Name : {{person.fName}}</p>
<p>Last Name : {{person.lName}}</p>

And use ng-controller.