【问题标题】:Problems with Spring MVC 4.0 application with Restful routing and AngularJS routing带有 Restful 路由和 AngularJS 路由的 Spring MVC 4.0 应用程序的问题
【发布时间】:2014-11-20 00:19:37
【问题描述】:

我有一个 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 文件中设置,对我的 restful 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 错误。

【问题讨论】:

  • 你能发布你的调用网络服务的服务定义吗?
  • 为什么不使用 $resource 而不是 $http ?由于您正在处理 REST 端点
  • 除了我查看的各种代码示例之外,我不确定是否使用了 $http,而不是 $resource。
  • @MLefebvre - 你找到任何解决方案了吗..即使我也面临同样的问题..

标签: java angularjs rest spring-mvc tomcat7


【解决方案1】:

尝试将您的 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);
    });

  }]);

【讨论】:

猜你喜欢
  • 2016-11-09
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2018-11-01
  • 2016-05-26
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多