【问题标题】:@Controller class is not redirecting to the specified page@Controller 类未重定向到指定页面
【发布时间】:2019-04-27 03:22:47
【问题描述】:

这是我的控制器类

@Controller
public class PageController {

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

我还有一个 RestController 类

@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 Application 类的@ComponentScan 中包含了所有必要的包。

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

调试时,控件实际上到达return "index";,但是页面没有显示。

【问题讨论】:

  • 你用的是什么模板引擎?请把pom文件贴在这里
  • “白标错误”也意味着您在服务器控制台上收到了一条信息性消息。

标签: java spring-boot spring-web


【解决方案1】:

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

@Configuration
public class MvcConfig implements WebMvcConfigurer {

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

}

【讨论】:

    【解决方案2】:

    默认视图解析器将在名为资源、静态和公共的文件夹中查找。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2011-08-15
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多