@kukkuz 几乎回答了“为什么?”这个问题。对于那些仍在研究“如何”的人,积累其他人的回答。
使用 RestController:
@RestController
public class MyRestController {
@RequestMapping("/")
public ModelAndView welcome() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login.html");
return modelAndView;
}
}
- 注意视图名称是:'login.html'(完整文件名)。
- 文件的位置也很重要,默认情况下 login.html 必须在 resources/static 或 resources/public 中
您可以为默认后缀设置应用程序参数,例如:
spring.mvc.view.suffix=.html
在这种情况下,视图名称必须不带“登录”之类的扩展名。
可以使用一些建议的百里香叶。
意味着您的 pom.xml 依赖项中有如下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.4</version>
</dependency>
在这种情况下,login.html 默认必须位于:resources/templates 文件夹中,并且调用类似,现在唯一的区别在于视图名称,因为 tymeleaf 使用 .html 作为默认值。
// fails by default
// NO fail if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html
// NO fail if thymeleaf is added, and there is a file login.html in a resources/templates folder.
@RequestMapping("/loginTest")
public ModelAndView loginTest () {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
使用控制器:
@Controller
public class MyController {
//gets html from a default 'resources/public' or 'resources/static' folder
@RequestMapping(path="/welcome")
public String getWelcomePage(){
return "login.html";
}
//gets html from a default 'resources/public' or 'resources/static' folder
@RequestMapping("/welcome1")
public ModelAndView getWelcomePageAsModel() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login.html");
return modelAndView;
}
// fails with 404 resource not found by default
// NO fail, if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html
// NO fail, if thymeleaf is added, and there is a file login.html in a resources/templates folder
@RequestMapping(path="/welcome2")
public String thisFails(){
return "login";
}
}