使用Thymeleaf和Angular在JHipster中进行服务器/客户端路由

Ham*_*Guy 2 routing angularjs single-page-application thymeleaf jhipster

背景:我是一名法国开发人员,在团队中开发基于JHipster的众筹平台.

在JHipster中,当访问http://domain.com/unknown时,检索到的页面是服务器端错误页面.

我想知道的是: - 百里香叶如何知道它必须返回error.html? - 参数来自何处以及它们如何,特别是对于变量等

<span th:text="${error}">
Run Code Online (Sandbox Code Playgroud)

- >错误来自哪里(状态和消息相同)?某处有某种服务器端控制器吗?

另一个问题是必然结果:为什么jhipster中有2个错误页面,一个客户端和一个服务器?不应该只有一个客户端页面,因为JHipster是用于SPA.为什么服务器不总是发送回index.html,让客户端测试是否有错误?

最后一个问题也是必然结果:是否有某种方法可以在客户端(角度)路由(app.js文件)中请求动态服务器端(百万美元)模板.这对于开发丰富的SPA非常有用.

PS:谢谢Julien的工作

Joh*_*n R 7

我想知道的是: - 百里香叶如何知道它必须返回error.html?

两部分.首先,Spring配置为使用Thymeleaf用于所有服务器端视图.在JHipster中,应用程序注释如下:

@ComponentScan
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
public class Application {
Run Code Online (Sandbox Code Playgroud)

@EnableAutoConfiguration是理解Thymeleaf如何设置的关键.它会触发ThymeleafAutoConfiguration,它会创建Thymeleaf视图解析器和诸如此类的东西.请注意,JHipster有一个ThymeleafConfiguration类,但这仅用于电子邮件,与您的问题无关.

第二部分... Spring Boot使用"/ error"作为默认错误视图.来自文档:

Spring Boot默认提供/错误映射,以合理的方式处理所有错误,并在servlet容器中注册为"全局"错误页面.对于机器客户端,它将生成一个JSON响应,其中包含错误,HTTP状态和异常消息的详细信息.对于浏览器客户端,有一个"whitelabel"错误视图,以HTML格式呈现相同的数据(要自定义它,只需添加一个解析为'错误'的视图).

解析错误视图时,Spring将为您正在使用的视图解析器添加正确的后缀(我描述的第一部分).例如,Thymleaf的.html,Velocity的.vm或Freemarker的.ftl.

某处有某种服务器端控制器吗?

是.JHipster也使用Spring Boot Actuator.查看文档的这一部分.感兴趣的主要类是ErrorMvcAutoConfiguration.特别是这部分:

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes();
}

@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
    return new BasicErrorController(errorAttributes);
}
Run Code Online (Sandbox Code Playgroud)

错误来自哪里(状态和消息相同)?

请参阅上面刚引用的代码,然后查看DefaultErrorAttributes:

Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
errorAttributes.put("timestamp", new Date());
// and so on...
Run Code Online (Sandbox Code Playgroud)

另一个问题是必然结果:为什么jhipster中有2个错误页面,一个客户端和一个服务器?不应该只有一个客户端页面,因为JHipster是用于SPA.为什么服务器不总是发送回index.html,让客户端测试是否有错误?

需要有一个服务器端错误处理程序.并非所有东西都会映射到Angular路线.例如,www.yoursite.com/doesnt_exist会导致浏览器向服务器发出另一个请求.

最后一个问题也是必然结果:是否有某种方法可以在客户端(角度)路由(app.js文件)中请求动态服务器端(百万美元)模板.这对于开发丰富的SPA非常有用.

是.您可以templateUrl在app.js中指定JS函数.