Search code examples
javaspring-bootspring-web

@Controller class is not redirecting to the specified page


This is my Controller class

@Controller
public class PageController {

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

And I also have a 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;
    }
}

I have included all the necessary packages in the @ComponentScan of the Spring Application class.

I tried placing the index.html page in both src/main/resources/static and src/main/resources/templates. But when I load localhost:8080 it shows Whitelabel error page.

While debugging, the control is actually reaching return "index"; , but the page is not displayed.


Solution

  • The default view resolver will look in folders called resources, static and public.

    So put your index.html in /resources/resources/index.html or /resources/static/index.html or /resources/public/index.html

    You also need to return the full path for the file and the extension

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

    This makes your html page publicly available (e.g. http://localhost:8080/index.html will serve up the page) If this isn't what you want then you'll need to look at defining a view resolver.