我的应用程序使用Spring Boot作为后端,使用Angular JS作为前端。
我使用Thymeleaf进行多语言支持。 Thymeleaf要求将所有html文件放在名为templates的文件夹下。
在前端,我使用angular的routeProvider来重定向页面。这是代码:
angular.
module("myapp").
config(function ($routeProvider) {
$routeProvider
.when( '/dashboard/:param1/:param2/', {
templateUrl: 'templates/pages/dashboard.html',
controller: 'dashboardController',
reloadOnSearch: false
})
.when( '/login/', {
templateUrl: 'templates/auth/login.html'
})
.otherwise({ redirectTo: '/dashboard/global/-1' });
});
在java方面,我的WebConfig.java中有一些ViewController代码
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/login").setViewName("auth/login"); //This works
registry.addViewController("/dashboard/**").setViewName("page/dashboard"); //Don't work, 404 error
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
登录页面有效,但对于仪表板,Angular给出了404错误。
获取http://localhost:8080/myapp/templates/pages/dashboard.html 404(未找到)
如果我将仪表板移出模板文件夹,并将templateUrl更改为
templateUrl: 'pages/dashboard.html',
Angular现在可以找到并显示仪表板页面,但是Thymeleaf不再有效,因为它不在模板文件夹中。我失去了多语言能力。
我看到login.html是一个完整的html页面,头部,正文; dashboard.html是index.html的一部分,所以它只是一个很大的div。
我对Spring MVC和Angular routerProvider感到困惑。在我的情况下可以使用ANGULARJS $ routeProvider吗?我应该只使用Spring MVC,因为我需要Thymeleaf来实现多语言能力吗?有什么建议?
答案 0 :(得分:0)
在Google上搜索主题后,我发现了这篇帖子的解决方案: Angular simple routing is not working
基本上,要使Thymeleaf工作,必须将html模板放在templates文件夹下。
对于Angular模板,如果您不需要Thymeleaf来处理模板,可以将html模板放在静态文件夹下,并在$ routeProvider中提供模板位置:
templateUrl: 'pages/dashboard.html', //the template is under static/pages
如果您确实需要Thymeleaf来处理模板,您必须将模板放在模板文件夹下,并在$ routeProvider中,您提供模板位置:
templateUrl: 'dashboard', //this is more like a nick name, there is no .html
这告诉Angular从后端Thymeleaf获取仪表板。在java方面,我们需要添加一个viewController来公开百日咳模板
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/login").setViewName("auth/login");//register controllers that will expose template
registry.addViewController("/dashboard/**").setViewName("pages/dashboard"); //At here, you mapping the nick name and indicate the template is actually located under templates/pages
//for Angular Directives
registry.addViewController("/breadcrumb").setViewName("directives/breadcrumb");
registry.addViewController("/flipcard").setViewName("directives/flipcard");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
对于模板,您可以将它们保存在一个大的div标签内,不需要添加标头和正文标记以使其成为完整的html。