@Controller class 没有重定向到指定页面

@Controller class is not redirecting to the specified page

这是我的控制器class

@Controller
public class PageController {

    @GetMapping(value="/")
    public String homePage() {
        return "index";
    }   
}

我还有一个 RestController class

@RestController
public class MyRestController {

    @Autowired
    private AddPostService addPostService;

    @PostMapping("/addpost")
    public boolean processBlogPost(@RequestBody BlogPost blogPost)
    {
        blogPost.setCreatedDate(new java.util.Date());
        addPostService.insertBlogPost(blogPost);

        return true;
    }
}

我已经在 Spring 应用程序 class 的 @ComponentScan 中包含了所有必需的包。

我尝试将 index.html 页面同时放在 src/main/resources/staticsrc/main/resources/templates 中。但是当我加载 localhost:8080 它显示 Whitelabel error page.

调试的时候,控件居然到达 return "index";,但是页面不显示

正确的行为之一是在配置中注册您的视图并将其保存在 src/main/resources/templates/index.html:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

}

默认视图解析器将在名为 resources、static 和 public 的文件夹中查找。

所以把你的 index.html 放在 /resources/resources/index.html 或 /resources/static/index.html 或 /resources/public/index.html

您还需要return文件和扩展名的完整路径

@Controller
public class PageController {
    @GetMapping(value="/")
    public String homePage() {
        return "/index.html";
    }   
}

这使您的 html 页面 public 可用(例如 http://localhost:8080/index.html 将提供该页面)如果这不是您想要的,那么您需要查看定义视图解析器。