Gautham M
Gautham M

Reputation: 4935

@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.

Upvotes: 0

Views: 114

Answers (2)

pcoates
pcoates

Reputation: 2307

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.

Upvotes: 1

uli
uli

Reputation: 671

One of the correct behavior is to register your view in configuration and keep it under src/main/resources/templates/index.html:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

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

}

Upvotes: 1

Related Questions