簡體   English   中英

如何在特定的URL上返回一些HTML文件-Spring Boot

[英]How to return some HTML file on specific URL - Spring Boot

我是Spring Boot的新手。 當用戶給我特定的網址時,我嘗試返回一些頁面。

我有兩頁:

\src\main\resources\static\index.html
\src\main\resources\static\admin.html

現在我有以下幾對:

GET / - return index.html
GET /admin.html - return admin.html

我想要以下對:

GET / - return index.html
GET /admin - return admin.html

我知道,我可以創建一些Controller ,然后可以使用批注@RequestMapping("/admin")並返回我的管理頁面。 但這需要很多動作。 如果我會有更多頁面,該怎么辦。

除了創建使用@RequestMapping定義所有方法的@Controller之外,還有另一種方法稍微方便一些,如果添加或刪除html文件,則無需更改。

選項1-如果您不介意別人看到.html后綴

將文件保留在靜態文件夾中,然后將WebMvcConfigurer添加到項目中,如下所示:

@Configuration
public class StaticWithoutHtmlMappingConfigurer extends WebMvcConfigurerAdapter implements WebMvcConfigurer {

    private static final String STATIC_FILE_PATH = "src/main/resources/static";

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        try {
            Files.walk(Paths.get(STATIC_FILE_PATH), new FileVisitOption[0])
                .filter(Files::isRegularFile)
                .map(f -> f.toString())
                .map(s -> s.substring(STATIC_FILE_PATH.length()))
                .map(s -> s.replaceAll("\\.html", ""))
                .forEach(p -> registry.addRedirectViewController(p, p + ".html"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        // add the special case for "index.html" to "/" mapping
        registry.addRedirectViewController("/", "index.html");
    }

}

選項2 –如果您希望在不使用html的情況下投放廣告並通過模板引擎進行解析

將您的html移到templates文件夾,啟用例如thymeleaf模板,並將配置更改為:

@Configuration
public class StaticWithoutHtmlMappingConfigurer extends WebMvcConfigurerAdapter implements WebMvcConfigurer {

    private static final String STATIC_FILE_PATH = "src/main/resources/static";

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        try {
            Files.walk(Paths.get(STATIC_FILE_PATH), new FileVisitOption[0])
                .filter(Files::isRegularFile)
                .map(f -> f.toString())
                .map(s -> s.substring(STATIC_FILE_PATH.length()))
                .map(s -> s.replaceAll("\\.html", ""))
                .forEach(p -> registry.addViewController(p).setViewName(p));

        } catch (IOException e) {
            e.printStackTrace();
        }

        // add the special case for "index.html" to "/" mapping
        registry.addViewController("/").setViewName("index");
    }

}

使用@RequestMapping(“ / admin”)注釋控制器方法,然后返回“ admin”並將admin.html放在模板目錄中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM