Angularjs 调用 java 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23273628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:37:05  来源:igfitidea点击:

Angularjs calling java functions

javajavascriptangularjsmongodb

提问by user3144600

I have one simple web application in JAVA and angularjs. Where users can add persons to app and remove them from mongo database.

我在 JAVA 和 angularjs 中有一个简单的 Web 应用程序。用户可以在其中向应用程序添加人员并将其从 mongo 数据库中删除。

My problem is, I don't know exactly how angular communicates with java and calls Java functions. For example if i want to delete a person from my database after a button click.

我的问题是,我不知道 angular 是如何与 java 通信并调用 Java 函数的。例如,如果我想在单击按钮后从我的数据库中删除一个人。

here's some code

这是一些代码

persons.html

人员.html

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

app.js

应用程序.js

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


 app.config(function ($routeProvider) {
    $routeProvider
      .when('/home', {
           templateUrl: '/partials/home.html',
           controller: 'HomeCtrl'
      })
      .when('/speakers', {
          templateUrl: '/partials/person-list.html',
          controller: 'PersonListCtrl'
      })
});
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

人员服务.js

app.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

人员资源.js

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

});

});

also i have a java class where i want to delete this person from database

我也有一个 java 类,我想从数据库中删除这个人

PersonResource.java

人员资源.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() returns MongoTemplate.

getTemplate() 返回 MongoTemplate。

Can anyone tell me what i am doing wrong to get my entry deleted from database ?

谁能告诉我从数据库中删除我的条目我做错了什么?

回答by Raul Claus

You need to attack the issues individually. Try testing your rest service alone. Use POSTMAN or any other REST Client (https://addons.mozilla.org/en-US/firefox/addon/restclient/) and test if the service is behaving accordingly. Only when that's successful, check on the Javascript client (AngularJS code) and see if the request (headers, params and body) is the same as the one generated by the REST client.

您需要单独解决这些问题。尝试单独测试您的休息服务。使用 POSTMAN 或任何其他 REST 客户端 ( https://addons.mozilla.org/en-US/firefox/addon/restclient/) 并测试服务是否相应地运行。仅当成功时,检查 Javascript 客户端(AngularJS 代码)并查看请求(标头、参数和正文)是否与 REST 客户端生成的相同。

回答by dev_in_progress

So when using GET method usual we fetch some data, if we want to send some data to server (ex. an id for person to be deleted) we use POST method or DELETE method, in my example I'll use POST method for simplification. Angular and java communicate thru RESTFUL services (JAX-RS), You cant call java function in angular js or vice verse. I'll show simple example of fetching data and sending data (fetch all persons, delete person with given id).

因此,当我们通常使用 GET 方法获取一些数据时,如果我们想将一些数据发送到服务器(例如要删除的人的 id),我们使用 POST 方法或 DELETE 方法,在我的示例中,我将使用 POST 方法进行简化. Angular 和 java 通过 RESTFUL 服务 (JAX-RS) 进行通信,您不能在 angular js 中调用 java 函数,反之亦然。我将展示获取数据和发送数据的简单示例(获取所有人员,删除具有给定 id 的人员)。

Here is an example where You can start learning from:

下面是一个示例,您可以从中开始学习:

Java Person Controller

Java 人控制器

@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

Java 个人服务

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

Java 人员存储库

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

      public List<Person> findAll();
}

Angular app.js

Angular 应用程序.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

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

Hope it will help, not tested but generally that is the flow..send request to controller with person id, find it in database and delete it

希望它会有所帮助,未经测试,但通常是流程..向带有人员 ID 的控制器发送请求,在数据库中找到它并删除它

回答by Siddharth Rathi

you can call java method or service in angularjs controller this way:

您可以通过以下方式在 angularjs 控制器中调用 java 方法或服务:

app.controller('personCtrl',['$scope', '$http', function($scope, $http){
    $scope.firstName = "John";
    $scope.personList = [];
    $scope.typelistload = function() {
        $http.get(
            'http://localhost:8080/SpringMVCHibernate/Person/getPersonList'
        ).success(function(data) {
            $scope.personList = data;
        }).error(function() {
            ngToast.danger( "Some problem in Listing:");
        });
    };
}]);