我是Spring Boot的新手。当用户给我特定的URL时,我尝试返回一些页面。
我有两页:
GET / - return index.html
GET /admin.html - return admin.html
现在我有以下几对:
GET / - return index.html
GET /admin - return admin.html
我想要以下几对:
Controller
我知道,我可以创建一些@RequestMapping("/admin")
,然后我可以使用注释{{1}}并返回我的管理页面。但它需要这么多的行动。如果我有更多的页面怎么样呢。
答案 0 :(得分:2)
除了使用@Controller
创建定义所有方法的@RequestMapping
之外,还有另一种方法更方便,如果添加或删除html文件则无需更改。
选项1 - 如果您不介意人们看到.html后缀
将您的文件保留在 static 文件夹中,并在项目中添加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移至模板文件夹,例如启用百万美元模板并将配置更改为:
@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");
}
}
答案 1 :(得分:1)
使用@RequestMapping(“/ admin”)注释控制器方法,而不是返回“admin”,并将admin.html放在模板目录中。