2016-09-04 124 views
1

我想製作一些彈簧啓動應用程序。我已經創建了spring引導項目,但是我遇到了問題。我的控制器看起來像:Spring Boot和AngularJS

@RestController 
public class IndexController { 

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

但我看到的所有內容不是index.html,而只是一個詞「索引」。 因此我想要使用角度。

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 

我如何才能使這個角度控制器的工作原理和返回正確的意見?

回答

0

應該有一流的那樣:

@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(); 
    } 
} 
1

我認爲你的設置應該工作,如果你實際上綁定/index作爲請求映射,而不是/home

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

假設你沒有一些隨機@EnableWebMvc註釋的地方配置,殺死你的初始啓動設置。

+0

它的工作原理,但它表明我只有一個字「指數」。控制器不搜索index.html。 ('/','index') .when('/ index','index') –

+1

然後用'@ Controller'替換'@ RestController' – EpicPandaForce

+0

我用角度和這個提供者:$ routeSegmentProvider 。猜猜你應該在類名之前使用@RequestMapping()。 –

1

@EpicPandaForce有正確的答案。你想使用@Controller,而不是@RestController@RestController是一個元註釋@Controller@ResponseBody@Controller將搜索已註冊的ViewResolver s,而@RestController不會。

0

當你使用@RestController時,spring不使用視圖解析器。所以,你應該改變@RestController到@Controller