繁体   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