草庐IT

java - Angularjs调用java函数

coder 2023-05-05 原文

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

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

这里有一些代码

persons.html

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

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

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

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

});

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

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);
  }

getTemplate() 返回 MongoTemplate。

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

最佳答案

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

这是一个你可以开始学习的例子:

Java 人物 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 人员服务

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 人员存储库

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>

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

关于java - Angularjs调用java函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273628/

有关java - Angularjs调用java函数的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐