Utilizing AngularJS to invoke Java functions

Currently, I am working on a web application using JAVA and AngularJS. The application allows users to add and remove persons from a MongoDB database.

One issue I am facing is how AngularJS communicates with Java to call Java functions. Specifically, I am unsure about the process of deleting a person from the database after a button click.

Below is a snippet of the code:

persons.html

<a for-authenticated ng-click="remove(s.id)" href=""> <i
     class="pull-right glyphicon glyphicon-remove"></i>
</a>

app.js

angular.module('conferenceApplication', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.bootstrap',
'angularFileUpload',
'ngQuickDate'])

 .config(function ($routeProvider) {
    $routeProvider
      // Define routes here
      });
      
app.controller('PersonListCtrl', function ($scope,$http, $modal, $log, $route, PersonService) {
$scope.remove = function(id) {
    var deletedPerson = id ? PersonService.remove(id, function(resp){
        deletedPerson = resp;
    }) : {};
};
}

PersonService.js

angular.module('conferenceApplication')
.service('PersonService', function ($log, $upload, PersonResource) {
this.getById = function (id, callback) {
    return PersonResource.get({personId: id}, callback);
};
this.remove = function(id, callback) {
    return PersonResource.deleteObject({PersonId: id}, callback);
}
});

PersonResource.js

angular.module('conferenceApplication')
.factory('PersonResource', function ($resource) {
return $resource('rest/person/:personId',
    {
        personId: '@personId'
    },
    {
        'update': { method: 'PUT' }
    })
});

Furthermore, there is a Java class responsible for deleting the person from the database:

PersonResource.java

@Controller
 @RequestMapping("/person")
   public class PersonResource {

     @Autowired
     private PersonService personService;

     @RequestMapping(method = RequestMethod.GET, value = "/{id}")
     public ResponseEntity<Person> deleteObject(@RequestBody Person id) {
        Person person = personService.findById(id);
        personService.deleteObject(id);
        return new ResponseEntity<Person>(person, HttpStatus.ACCEPTED);
     }
   }

PersonRepository

  @Override
  public void deleteObject(String id) {
      getTemplate().remove(new Query(Criteria.where("id").is(id)), Person.class);
  }

The `getTemplate()` function returns a MongoTemplate.

If anyone has insights into what might be causing issues with deleting entries from the database, your feedback would be greatly appreciated!

Answer №1

Typically, when using the GET method, we retrieve data. If we need to send data to the server (such as an ID for a person to be deleted), we can use either the POST or DELETE methods. In this example, I'll demonstrate using the POST method for simplicity. Angular and Java communicate through RESTful services (JAX-RS); you cannot call a Java function in AngularJS, or vice versa. Below is a simple example of fetching data and sending data (fetching all persons and deleting a person with a given ID).

Here's a sample code snippet to get you started:

Java Person Controller

@Controller
@RequestMapping(value = "/person")
public class PersonController{

    private final PersonService personService;

    @Autowired
    public PersonController(final PersonService personService) {
        this.personService= personService;
    }

    @RequestMapping(value = "/", method = { RequestMethod.GET })
    @ResponseBody
    public List<Person> getPersons() {
        return personService.getPersons();
    }
    @RequestMapping(value = "/delete/{personId}", method = { RequestMethod.POST})
    @ResponseBody
    public HttpStatus deletePerson(@PathVariable final long personId) {
        return personService.deletePerson(personId);
    }
}

Java Person Service

public class PersonService{

    private final PersonRepository personRepository;

    @Autowired
    public PersonService(final PersonRepository personRepository) {
       this.personRepository= personRepository;
    }

    public List<Person> getPersons() {
        return personRepository.findAll();;
    }

   public HttpStatus deletePerson(final long id) {
       if (id > 0) {
           personRepository.delete(id);
           return HttpStatus.OK;
       } else {
           return HttpStatus.INTERNAL_SERVER_ERROR;
       }
   }
}

Java Person Repository

public interface PersonRepository{
      public void delete(int personId);

      public List<Person> findAll();
}

Angular app.js

(function() {
    var app = angular.module('personApp',[]);

    app.controller('personCtrl',function($scope,$http){

        $scope.getPersons = function(){
            $http.get('person/').success(function(response){
                $scope.allPersons = response.data;
            }).error(function(){
               //handle error
            })
        };

        $scope.deletePerson = function(personId){
            $http.delete('person/'+personId).success(function(response){
                $scope.deleteResponseStatus = response.status;
            }).error(function(){
               //handle error
            })
        }
    })
})();

Html

<html ng-app="personApp">
   <body ng-controller=""personCtr>
      <input type="submit" ng-click="getPersons()"/>
      <input type="submit" ng-click="deletePerson(somePersonIdFromTableOrSomething)"
   </body>
</html>

This should give you a basic understanding of how to send a request to the controller with a person ID, locate it in the database, and delete it. Good luck!

Answer №2

To effectively address the issues, it is important to tackle each one individually. Begin by testing your REST service in isolation. Utilize tools like POSTMAN or any other REST Client (https://addons.mozilla.org/en-US/firefox/addon/restclient/) to verify if the service is functioning as expected. Once this test is successful, proceed to examine the Javascript client (specifically AngularJS code) and compare its request (headers, parameters, and body) with that generated by the REST client.

Answer №3

If you need to access a Java method or service from an AngularJS controller, you can do it like this:

app.controller('userController',['$scope', '$http', function($scope, $http){
    $scope.userName = "Alice";
    $scope.userList = [];
    $scope.loadUsers = function() {
        $http.get(
            'http://localhost:8080/SpringMVCHibernate/User/getUserList'
        ).then(function(response) {
            $scope.userList = response.data;
        }).catch(function() {
           toastr.error( "Error fetching user list");
        });
    };
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating interactive shapes in a 2D scene using Three.js and custom attributes

Recently, I created a 2D floorplan drawing using three.js. The shape was incorporated into the drawing with the following code snippet: var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3(50, 0, 90), new THREE.Vector3(1 ...

What may be causing the lag in the translation within ThreeJS?

Just started diving into ThreeJS and discovering its capabilities. Playing around with a simple example of creating a white dot and applying a basic translation. let dotGeometry = new THREE.Geometry(); let dotMaterial = new THREE.PointsMaterial({ size: ...

What is the process of sending a message between two servlets using apacheMQ?

I am currently working on integrating ApacheMQ into my web application that runs on Tomcat. I have come across some tutorials on local integration, as I do not plan to implement global integration. However, I am finding the tutorials to be quite confusing ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

What is the best way to confirm that my TypeScript string contains exactly two words?

Can you provide guidance on how to validate that a string contains exactly two words using TypeScript? I'm looking to implement this validation in order to ensure that I only call the server if the name is in "first last" format. ...

Implementing re-render logic for a React functional component based on changes in useState()

I've created a basic functional component that retrieves a date from localStorage and displays it. The component includes two buttons to add or remove weeks from the date, expecting the updated date to be shown. However, I'm facing an issue where ...

When running "npx create-nuxt-app" followed by "npm run dev", an error occurs stating that there

Recently, I started using Nuxt and initiated my app with npx create-nuxt-app my-app, setting the parameters as follows: Project name: client Programming language: JavaScript Package manager: Npm UI framework: Tailwind CSS Nuxt.js modules: Axios - Prom ...

oracle jdbc number is not valid

Attempting to run the query below: String query = "select NUMERO_CHAUFFEUR, avg(DISTANCE) as DISTANCE " + "from " + "(select NUMERO_CHAUFFEUR, " + "6387.7 * ACOS((sin(LATITUDE_DEPART / 57.29577951) * SIN(LA ...

Submitting a File Using AngularJS and PHP

Attempting to upload a file utilizing Angular JS and PHP through a formdata object. Wanting to utilize key1 (data) value as JSON to transmit filename and user info to the php script Opting for key2 (uploadFile), value being the file currently being uploa ...

Issue with Ajax reappearing the second time

Currently, I am experiencing an issue with the sorting function on search results. After performing a search, if I try to change the value in the dropdown for filtering the number of results per page, it works fine for the first time. However, upon further ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

Storing a dynamically created grid of inputs using a consistent ng-model

I have the following code snippets: $scope.createPack = function(informationsPack, informationsActivite) { PackService.add(informationsPack, informationsActivite) .then(function(res) { $state.go(&apos ...

"Implementing a feature in React JS react-table to dynamically add a new column when a

I'm struggling to add a new column to react-table when a button is clicked. Even after re-rendering the table with a flag, I can't seem to add the new column. Can anyone suggest where I might be going wrong? Here's the link to the executable ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

"Enhance Your Website with jQuery UI Tooltips Featuring HTML Content

Is there a way to customize the appearance of tooltips using jQuery UI Tooltip? I want to format tooltips similar to the image shown below for HTML content. Example: JavaScript: $(function () { $.widget("ui.tooltip", $.ui.tooltip, { optio ...

"Integrating JavaScript files into HTML using Flask: A step-by-step guide

I have created an HTML page with a JavaScript section where I am importing various other .js files: <script type="module"> import * as THREE from "../build/three.module.js"; import { OrbitControls } from ...

What is the best way to transfer a JavaScript integer as an integer to PHP?

<script type="text/javascript"> var int_val = 111; </script> <?php $js_int_val_in_php ='<script>document.write(int_val);</script>'; echo $js_int_val_in_php; // 111 echo '<br>'; echo ...

display saved data from ajax request

I've been working on saving data and files using ajax. Following a tutorial (link), I managed to successfully save the data in the database and the image files in the designated folder. However, I'm facing an issue where the success or error mess ...

Creating a web form with HTML and integrating it with jQuery AJAX

Looking to fetch data from the server through jQuery AJAX on an HTML form and store the response in a PHP string variable. Here is my current code snippet: <form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe"> &l ...

What is the best method to determine if an object includes a specific string?

While I can read values inside the object as the h tags get populated, for some reason I am unable to hit the statements checking response.image for a value, despite confirming its existence through console.log. I'm not entirely sure if the code belo ...