![](/img/trans.png)
[英]Cannot access SwaggerUI index.html page, but can open api-docs (Spring - Boot)
[英]Cannot display the index.html page in Spring boot
我試圖創建一個簡單的spring boot應用程序
我創建了spring boot應用程序類,配置類,控制器類和index.html。
我添加了Thymeleaf依賴項並將html頁面放在資源文件夾(\\ src \\ main \\ resources \\ templates \\ index.html)下
但是當我運行應用程序時,它給出了一個錯誤
org.thymeleaf.exceptions.TemplateInputException:
Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers
請給我一個解決方案。
@SpringBootApplication
@ComponentScan(basePackages = {"com.mail"})
public class SpringBootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
控制器類
@RestController
public class IndexController {
@RequestMapping(value="/", method = RequestMethod.GET)
String index(){
System.out.println("..............hit");
return "index";
}
Web配置的胸腺
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
index.html頁面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Framework</title>
</head>
<body>
<h1> Hello Spring Boot </h1>
</body>
</html>
嘗試執行以下操作:
嘗試將@RestController替換為@Controller。 我將從start.spring.io生成的模板開始。 並一步一步地添加功能。
要么
如果您只是進行一些谷歌搜索,就可以輕松地從這里開始找到一些實際可行的樣本百里香葉項目。
看起來靜態資源默認情況下不可訪問。 嘗試通過添加資源處理程序來提供對靜態資源的訪問,例如:
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("");
}
}
如先前的答案所述, @RestController
應該替換為@Controller
。
當我們使用@RestController時 ,return語句的值將作為String Response發送。 但是,當我們使用@Controller時 ,return語句的值將被視為要呈現的視圖。
請參閱差異。 黑白@RestController和@Controller
另外,當我們使用Thymeleaf之類的模板引擎時,Spring Boot將自動在'\\ src \\ main \\ resources \\ templates \\'中查找index.html ,這是Spring Boot中視圖的默認位置。 請參閱Spring Boot和模板引擎 。
因此,我們不需要顯式定義WebConfiguration類,因為然后我們需要使用ViewRegistry定義在XML文件或Java類中配置的視圖解析器。 Spring Boot消除了對XML和Java View Registry的需要。 因此,您也可以取消WebConfiguration類。
在此處閱讀第2點。
在pom中添加以下依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.