【问题标题】:Can angular take over java controller functionalities?角度可以接管java控制器功能吗?
【发布时间】:2017-03-08 20:19:15
【问题描述】:

我目前正在尝试使用 springboot、java 和 angular js 构建单页应用程序。我有一个多页应用程序,其中我的 java 控制器处理所有路由。现在我实现了 Angular js 路由,它与我的控制器发生冲突。我需要找到一种方法将此控制器重写为 angular,以便我的值可以正确显示在 UI 上。

@Controller
public class IndexController {      
    @Autowired
    JAXSample index;    
    @Autowired
    VD_Repo vdRepo;
    @Autowired
    PD_Repo pdRepo;
    @Autowired
    CH_Repo chRepo;     

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index(Locale locale) throws MalformedURLException {
        ModelAndView model = new ModelAndView("index");    
        return model;
    }

    @RequestMapping(value = "/getValues", method = RequestMethod.GET)
    public ModelAndView getvalues(Info  info) throws MalformedURLException {

        ModelAndView model = new ModelAndView("getvalues");
        model.addObject("Haddress", info.getHouseAddress());

        dCert custinfo = index.readXML(info.getHouseAddress());
        model.addObject("custinfo", custinfo);
        model.addObject("checked", true);           
        model.addObject("ch", chRepo.getAll(info.getHouseAddress()));
        model.addObject("pd", pdRepo.getAll(info.getHouseAddress()));
        model.addObject("vd", vdRepo.getAll(info.getHouseAddress()));

       return model;
    }

角度脚本

var App = angular.module('App', ['ngRoute']);
     App.config(function($routeProvider) {
    $routeProvider

        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        .when('/getValues', {
            templateUrl : 'pages/getValues.html',
            controller  : 'detailsController'
        });
});

App.controller('mainController', function($scope) {

        $scope.message = 'This is Home page';
    });

    App.controller('valuesController', function($scope) {
        $scope.message = 'This is Values';
    });

我上面的控制器基本上采用用户输入的值并通过 jaxb 运行它,并根据用户输入的值解组其余 api。

尝试

1) 如果我有这个控制器和我的 Angular js 路由同时运行,我要么没有得到部分视图,要么出现错误 404。

2) 如果我删除我的控制器,我有我的部分视图,但没有值来自 sql 或 jaxb 解组。

3) 尝试从 ModelAndView 切换到仅模型(仅在页面上呈现数据)。仍然给我错误,页面无法加载。

类似post

【问题讨论】:

    标签: javascript java angularjs spring-boot jaxb


    【解决方案1】:

    下面是 Angular JS 1 和 Spring 通信时最常用的方法之一。

    聪明的人使用不同的方法/口味。

    我建议你尝试以下方式

    首先创建带有注解@RestController的新控制器,然后有适当的HTTP方法进行正常操作,在此处详细查找Rest Maturity模型 https://martinfowler.com/articles/richardsonMaturityModel.html;

    package com.mycompany.userinfo.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.util.UriComponentsBuilder;
    
    import com.mycompany.userinfo.model.User;
    import com.mycompany.userinfoc.service.UserService;
    
    @RestController
    public class UserRestController {
    
        @Autowired
        UserService userService;  //Service which will do all data retrieval/manipulation work
    
    
        //-------------------Retrieve All Users--------------------------------------------------------
    
        @RequestMapping(value = "/user/", method = RequestMethod.GET)
        public ResponseEntity<List<User>> listAllUsers() {
            List<User> users = userService.findAllUsers();
            if(users.isEmpty()){
                return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
            }
            return new ResponseEntity<List<User>>(users, HttpStatus.OK);
        }
    
    
    }
    

    然后客户端创建Angular服务(它最适合进行后端调用,在不同组件之间共享数据)以使用如下的角度HTTP服务调用后端Spring控制器方法

    user.service.js
    'use strict';
    
    angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
    
        var REST_SERVICE_URI = 'http://localhost:8080/UserBackend/user/';
    
        var factory = {
            fetchAllUsers: fetchAllUsers
          };
        return factory;
    
        function fetchAllUsers() {
            var deferred = $q.defer();
            $http.get(REST_SERVICE_URI)
                .then(
                function (response) {
                    deferred.resolve(response.data);
                },
                function(errResponse){
                    console.error('Error while fetching Users');
                    deferred.reject(errResponse);
                }
            );
            return deferred.promise;
        }
    
    }
    

    最后是你的 Angular 控制器(它根据视图被创建和销毁,它与你的 html 模板紧密耦合,所以理想情况下永远不要从这个控制器直接调用后端,使用 Angular 服务)

    user.controller.js
    
    'use strict';
    
    angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
        var self = this;
        self.users=[];          
    
        fetchAllUsers();
    
        function fetchAllUsers(){
            UserService.fetchAllUsers()
                .then(
                function(d) {
                    self.users = d;
                },
                function(errResponse){
                    console.error('Error while fetching Users');
                }
            );
        }
    
    }]);
    

    1) Spring Controller 和 Angular JS 控制器是没有关系的。

    2) 当在RequestMapping("/user/")中定义一些东西时,那么执行那个方法的URL就变成了这样http://yourdomain.com或者localhost:port/applicationname/user/

    3) 从 Angular JS 中点击您需要使用 http 服务的 URL,如下所示

    $http.get("http://yourdomain or localhost:port/appname/user/")
                .then(sucessFunction(data){
                //This is callback function, a asynchronous call
                //This will get called on success of http request
            },
            failureFunction(error){
                //This is callback function, a asynchronous call
                //This will get called on failure of http request
            });
    Read more about anguls js service , http service and promise.
    

    我强烈建议您阅读文档或 Angular js 培训。

    希望这可以帮助您并消除您的疑虑。

    【讨论】:

    • java部分我懂,但是到js的时候完全迷路了,能不能多解释一下js文件?
    • Angular JS 控制器和 Spring 控制器没有任何关系,都是独立的。
    • 通过您的示例,我将如何更改它以使其遵循 SPA 格式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多