簡體   English   中英

帶有靜態路由和AngularJS路由的Spring MVC 4.0應用程序的問題

[英]Problems with Spring MVC 4.0 application with Restful routing and AngularJS routing

我有一個Spring MVC 4.0 AngularJS應用程序,當在同一實例上運行時,似乎在Restful接口路由和AngularJS路由之間存在沖突。 它會導致404錯誤。 我認為我沒有正確設置應用程序。

該應用程序捆綁在UserManager.war文件中,並復制到獨立運行(未嵌入在IDE中)的Tomcat 7.0實例上的webapps目錄中。

該應用程序在以下位置運行:

http://localhost:8080/UserManager/main
http://localhost:8080/UserManager/update
http://localhost:8080/UserManager/insert

Restful接口指定了以下URL:

http://localhost:8080/UserManager/services/users/list
http://localhost:8080/UserManager/services/users/{id}
http://localhost:8080/UserManager/services/users/insert
http://localhost:8080/UserManager/services/users/update/{id}
http://localhost:8080/UserManager/services/users/delete/{id}

這是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     id="WebApp_ID" version="3.0"> 
<display-name>User Manager Application</display-name>

<servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping> 
</web-app>

這是我的rest-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="localhost.rest.controller" />
<mvc:annotation-driven />
</beans>

這是我的UserManagerControler.java

package localhost.rest.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.springframework.http.HttpStatus;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/services")
public class UserManagerControler{

    @RequestMapping(value = "/users/list", method = RequestMethod.GET, headers="Accept=application/json")
    public @ResponseBody String getUsers() {

    }

    @RequestMapping(value = "/users/{pid}", method = RequestMethod.GET, headers="Accept=application/json")
    public @ResponseBody String getUserById(@PathVariable String pid) {

    }

    @RequestMapping(value = "/users/insert", method = RequestMethod.PUT, headers="Accept=application/json")
    public ResponseEntity<User> createUser(@RequestBody User user) {

    }

    @RequestMapping(value = "/users/update/{pid}", method = RequestMethod.POST, headers="Accept=application/json")
    public ResponseEntity<User> updateUser(@PathVariable String pid, @RequestBody User user) {

    }

    @RequestMapping(value = "/users/delete/{pid}", method = RequestMethod.DELETE, headers="Accept=application/json")
    public  ResponseEntity<String> deleteUser(@PathVariable String pid) {

    }

}

這是我的app.js ,它設置了AngularJS路由:

angular.module('PMApp', [ 'ngRoute', 'ui.bootstrap', 'PMApp.services' ])
.config(
        [ '$routeProvider', '$locationProvider', '$httpProvider',
                function($routeProvider, $locationProvider, $httpProvider) {

                    $locationProvider.html5Mode(true);

                    $routeProvider.when('/main', {
                        controller : 'MainController',
                        templateUrl : 'app/partials/main.html'
                    }).when('/insert', {
                        controller : 'InsertController',
                        templateUrl : 'app/partials/insert.html'
                    }).when('/update', {
                        controller : 'UpdateController',
                        templateUrl : 'app/partials/update.html'
                    }).otherwise({
                        redirectTo : '/main'
                    });

                } ]

).run(function($rootScope, $window, $location) {
    $rootScope.initialized = true;
});

控制器在controller.js文件中設置,對我寧靜的Web服務的調用在services.js文件中執行。

services.js

(function () {
    var userService = function ($http, $window, $q, $log, $rootScope) {

        var factory = {};

        factory.createUser = function (userId, last, first, sex, age, ethnicity, rank, dob) {
            var url = '/UserManager/services/users/insert';

            var parameters = {
                "userId" : userId,
                "last" : last,
                "first" : first,
                "sex" : sex,
                "age" : age,
                "ethnicity" : ethnicity,
                "rank" : rank,
                "dob" : dob
            };

            return $http.put(url, parameters)
                .then(function (data, status) {
                    return data;
                });
        };

        factory.deleteUser = function(userId) {
            var url = '/UserManager/services/users/delete/' + userId;
            return $http.delete(url)
                .then(function (data, status) {
                    return data;
                });
        };

        factory.updateUser = function (userId, last, first, sex, age, ethnicity, rank, dob) {
            var url = '/UserManager/services/users/update/' + userId;


            var parameters = {
                "userId" : userId,
                "last" : last,
                "first" : first,
                "sex" : sex,
                "age" : age,
                "ethnicity" : ethnicity,
                "rank" : rank,
                "dob" : dob
            };

            return $http.post(url, parameters)
                .then(function (data, status) {
                    return data;
                });
        };

        factory.getUsers = function () {
            var url = '/UserManager/services/users/list';

            return $http.get(url)
                .then(function (response) {
                    return response.data;
                });
        };

        factory.getUser = function (userId) {
            var url = '/UserManager/services/users/' + userId;

            return $http.get(url)
                .then(function (response) {
                    return response.data;
                });
        };

        return factory;
    }

    var app = angular.module("PMApp.services", ['ngResource']);
    app.factory('userService', userService);
}());

我可以使Web服務正常工作,但隨后在應用程序上出現404錯誤。 如果我調整web.xml,則可以啟動應用程序,但是對Web服務的調用失敗,並顯示404錯誤。

嘗試將您的var更改為:

url = '/{webapp-name}/services/users/insert'

嘗試使用以下測試工具: https : //chrome.google.com/webstore/category/app/11-web-development來檢查您是否可以訪問RESTful端點,並返回Mime類型application / json

同樣出於調試目的,它可能有助於放置錯誤處理塊,例如:

       $http.get(url)
        .then(function (response) {
            return response.data;
        }).error(function () {               
            // error happened           
       });

並檢查瀏覽器的控制台和服務器的日志文件,以查看是否顯示任何錯誤消息。

另外,由於您要處理RESTful端點,因此不嘗試使用$ resource而不是$ http,例如:

服務:

services.factory('ProductService', ['$resource',
  function($resource){  
    return $resource('/mywebapp/rest/product/:id',
            {
            id: "@id"           
            }
    );
  }]);  

控制器:

controllers.controller('ProductListCtrl', ['$scope', 'ProductService',
  function($scope, ProductService) {

    ProductService.query(function(data) {
        $scope.products = data;
        $scope.productListNotEmpty = ($scope.products.length > 0);
    });

  }]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM