0

I am currently trying to build a single page application with springboot, java, and angular js. I had a multi-page application where my java controller handles all the routes. Now that I implemented angular js routes, it is conflicting with my Controller. I need to find a way to rewrite this controller as angular so that my values can be properly displayed on the 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;
    }

Angular script

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

My controller above basically takes the value a user inputs and run it through jaxb and unmarshall the rest api based on the value user inputted.

Attempts

1) If I have this controller and my angular js routes running simultaneously, I either not get the partial views or error 404.

2) If I remove my controller, I have my partial views but no values are coming in from sql, or jaxb unmarshalling.

3) Tried switching from ModelAndView to just model (just to render the data on the page). Still giving me error, page cannot load.

Simliar post

1 Answer 1

0

Below is one of mostly used approach when Angular JS 1 and Spring communication is there.

Like wise people use different approach/ Flavors.

I suggest you try for following way

First of all create new controller with annotation @RestController, then have proper HTTP method for proper operation, look for Rest Maturity model in detail here 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);
    }


}

Then client side create Angular Service( It is singleton best for having back end call, sharing data between different component) for calling Back end Spring controller method using angular HTTP service like below

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

}

Then finally comes your Angular Controller(It get created n destroyed as per view, it is tightly coupled with your html template, So ideally never have any direct back end call from this controller, use angular service)

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 and angular JS controller are nothing do with each other.

2) When define something in RequestMapping("/user/"), So then URL to execute that method become like this http://yourdomain.com or localhost:port/applicationname/user/

3) Hit that URL from Angular JS you need to use http service like below

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

I strongle recommend you to go through documentation or angular js trainings.

Hope this helps you and clear your doubts.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand the java part, But when it came to the js I got totally lost, Can you explain more about the js files?
Angular JS Controller and Spring controller nothing do with each other, both are separate.
With your examples, How would I alter it so that it follows the SPA format?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.