简体   繁体   English

如何从 angular.js 调用 spring mvc REST 控制器?

[英]how do I call a spring mvc REST controller from angular.js?

How do I hook up an angularjs web form with a spring mvc REST controller, so that only a small fragment of a page is refreshed (instead of the entire page) when the form is submitted?如何将 angularjs Web 表单与 spring mvc REST 控制器连接起来,以便在提交表单时仅刷新页面的一小部分(而不是整个页面)?

In this case, only a string is refreshed in the page instead of refreshing the entire page.在这种情况下,页面中只会刷新一个字符串,而不是刷新整个页面。 Specifically, how do I alter the code below so that the only element on the page that refreshes from the server after form submit is <H1>${person.answer}</H1> .具体来说,我如何更改下面的代码,以便在表单提交后从服务器刷新的页面上唯一的元素是<H1>${person.answer}</H1>

NOTE: the code below has been edited to adhere to @Cotta's suggestions.注意:下面的代码已经过编辑以符合@Cotta 的建议。 I am replacing the original code with @Cotta's suggestions instead of appending because I want this to be easy to read.我正在用@Cotta 的建议替换原始代码而不是附加,因为我希望它易于阅读。

index.html is: index.html是:

<!DOCTYPE html>
<html>
<head>
    <!-- CSS ===================== -->
    <!-- load bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> 
    <style>
        body    { padding-top:30px; }
    </style>

    <!-- JS ===================== -->
    <!-- load angular -->
    <script src="http://code.angularjs.org/1.2.6/angular.js"></script> 
    <script src="app.js"></script>
</head>

<!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">

    <!-- PAGE HEADER -->
    <div class="page-header"><h1>What is your name?</h1></div>

    <!-- FORM -->
    <!-- pass in the variable if our form is valid or invalid -->
    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->

        <!-- NAME -->
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" class="form-control" ng-model="name" required>
        </div>

        <!-- SUBMIT BUTTON -->
        <button type="submit" class="btn btn-primary">Submit</button>

    </form>

</div><!-- col-sm-8 -->
</div><!-- /container -->
</body>
</html>
<!-- example from: https://scotch.io/tutorials/angularjs-form-validation -->  

app.js is: app.js是:

var validationApp = angular.module('validationApp', ['ngResource']);

validationApp.controller('mainController', ['$scope'], '$resource', function($scope, $resource) { 
  // function to submit the form after all validation has occurred            
  $scope.submitForm = function(isValid) {

    // check if form is valid before sending data to the server
    if (isValid) {
        var NameCheck = $resource('/api/namecheck', {});
        var result = NameCheck.get();
        console.log(result.answer);
    }

  };

});

RingRestController.java is: RingRestController.java是:

@RestController
@RequestMapping("/api")
public class RingRestController {

    @RequestMapping(value = "/namecheck", method = RequestMethod.POST)
    public @ResponseBody Person create(@RequestBody Person person) {
        String answer = "";
        if (person.getName().equals("Frodo") || person.getName().equals("frodo")){
            answer = "Frodo, would you please hold onto this ring for me?";
        }
        else {
            answer = "Thank you for telling us your name.";
        }
        person.setTransientAnswer(answer);
        return person;
    }

}  

NOTE: this uses the same core project as the angularjs branch of the spring petclinic sample app (I deleted everything in /src/main/webapp and built up new angularjs within the spring project shell. Thus, it uses the same spring.xml config files, which might be related to a solution. You can read the spring config files by clicking on this link .注意:这使用与 spring petclinic 示例应用程序的 angularjs 分支相同的核心项目(我删除了/src/main/webapp所有内容,并在 spring 项目 shell 中构建了新的 angularjs。因此,它使用相同的 spring.xml 配置文件,这可能与解决方案有关。您可以通过单击此链接阅读 spring 配置文件。

You may solve this by:您可以通过以下方式解决:

  1. Include ngResource in your application在您的应用程序中包含ngResource

     var validationApp = angular.module('validationApp', ['ngResource']);
  2. Inject $resource on your controller在您的控制器上注入$resource

     validationApp.controller('mainController', ['$scope', '$resource', function($scope, $resource) { ... }]);
  3. Then you may use $resource to create an object responsible for sending your requests inside submitForm :然后你可以使用$resource创建一个对象,负责在submitForm发送你的请求:

     var NameCheck = $resource('http://url-to-service', {}); var result = NameCheck.get(); console.log(result.answer);
  4. Remember to include angular-resource.js file.请记住包含 angular-resource.js 文件。

You may also do something similiar with $http and a few lines of code more.你也可以用$http和几行代码做一些类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM