代码之家  ›  专栏  ›  技术社区  ›  Gautham M

@控制器类未重定向到指定页

  •  0
  • Gautham M  · 技术社区  · 6 年前

    这是我的控制器课程

    @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;
        }
    }
    

    我已经把所有必要的包裹都包括在清单中了 @ComponentScan Spring应用程序类的。

    我试着把 index.html 两页都有 src/main/resources/static src/main/resources/templates .但当我加载 localhost:8080 它表明 Whitelabel error page .

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   pcoates    6 年前

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

    所以把你的索引。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 如果这不是你想要的,那么你需要看看如何定义一个视图解析器。

        2
  •  1
  •   uli    6 年前

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

    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
        }
    
    }