我正在尝试设置一个springboot+react js应用程序,并希望在同一个war存档中运行。所以多亏了网上的几个教程,我发现最好的方法应该是添加thymeleaf作为依赖项,然后制作一个指向react js build目录的自定义模板解析器。不知怎么的,这是行不通的。
我得到的错误是:
org.thymeleaf.exceptions.templateinputexception:解析模板[index]时出错,模板可能不存在,或者任何已配置的模板解析程序都无法访问模板
自定义解析程序的web配置:
@Controller
@EnableWebMvc
@ComponentScan
public class SpringWebConfig implements ApplicationContextAware,
WebMvcConfigurer {
private ApplicationContext applicationContext;
@Autowired
private SpringResourceTemplateResolver templateResolver;
@Autowired
private SpringTemplateEngine templateEngine;
public SpringWebConfig() {
super();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowCredentials(false).maxAge(3600);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/static/**",
"/favicon.ico",
"manifest.json"
)
.addResourceLocations(
"classpath:/public/static/",
"classpath:/public/favicon.ico",
"classpath:/public/manifest.json"
);
}
@Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/classes/public/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.setEnableSpringELCompiler(true);
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
}
前端控制器:
@Controller
public class FrontendController {
@GetMapping("**")
public String index() {
return "index";
}
}
tomcatwebapp文件夹中的结构(我已将war添加为root):
我做错什么了?或者有没有更好的方法来实现spring引导和react js在同一个war文件中运行?因为网上有很多帖子,所以选择了thymeleaf。
暂无答案!
目前还没有任何答案,快来回答吧!