繁体   English   中英

Spring Boot和AngularJS

[英]Spring Boot and AngularJS

我要制作一些春季启动应用。 我已经创建了spring boot项目,但是有问题。 我的控制器看起来像:

@RestController
public class IndexController {

    @RequestMapping(value="/home",method = RequestMethod.GET)
    public String homepage(){
        return "index";
    }
}

但是我所看到的不是index.html,而是一个单词“ index”。 因此,我想使用角度。

angular.module('mvcApp', [])
    .constant('MODULE_NAME', "index")
    .config(['$routeSegmentProvider', '$routeProvider', function ($routeSegmentProvider, $routeProvider) {
        $routeSegmentProvider
            .when('/', 'index')
            .when('/index', 'index')
            .when('/configuration', 'configuration')

        $routeSegmentProvider.segment('index', {
            templateUrl: 'HTML/index.html',
            controller: 'IndexCtrl'
        });

        $routeProvider.otherwise({redirectTo: '/'});
    }]);

和控制器:

angular.module('mvcApp').controller('IndexCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {

    $scope.hello = "Hello from AngularJS";

}]);

我的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello!</title>
</head>
<body ng-app="mvcApp" ng-controller="IndexCtrl">

Greeting page.
{{hello}}

</body>
</html>

但这不起作用,我在本地主机上仅看到错误。

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Sep 04 15:33:41 CEST 2016
There was an unexpected error (type=Not Found, status=404).
No message available

如何使该角度控制器工作并正确返回视图?

我认为,如果您实际上将/index绑定为请求映射,而不是/home ,则您的设置应该可以工作。

@RequestMapping(value="/index",method = RequestMethod.GET)
public String homepage(){
    return "index";
}

假设您没有某个随机的@EnableWebMvc注释的配置,该配置会@EnableWebMvc您的初始启动设置。

@EpicPandaForce有正确的答案。 您要使用@Controller而不是@RestController @RestController是具有@Controller@ResponseBody的元注释。 @Controller将搜索已注册的ViewResolver ,而@RestController不会。

当您使用@RestController时,spring不使用视图解析器。 因此您应该将@RestController更改为@Controller

应该有这样的课程:

@Configuration
public class ConfigurationMVC extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/HTML/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

暂无
暂无

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

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