Skip to content
Advertisement

Return HTML page with Spring Controller

So, apparently, I’m trying to return an HTML file with help of the Spring Controller.

I already have added Thymeleaf dependencies and also tried the following ways to configure it:

1.

@RequestMapping ("/")
@ResponseBody
public String homeDisplay() {
    return "homepage";
}
@Controller
public class HomeController {

@RequestMapping ("/")
public ModelAndView index () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("homepage");
    return modelAndView;
}
}

Anyway, didn’t help, I get Whitelabel Error Page.

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sun Dec 13 20:14:04 EET 2020 There was an unexpected error (type=Not Found, status=404). No message available

How can I fix it and display the HTML I need.

Advertisement

Answer

I was running in to a similar problem when trying to get a homepage to show up for a REST API that I was making. The project does not have Thymeleaf though. I used the following and this worked for me. The following code makes the home.html file, stored in resources/static to show up when the application starts. It’s a static page and no data is sent to it.

@Controller
public class HomeController {

    @RequestMapping("/")
    public String welcome() throws Exception {
        return "home.html"; //note that this says .html
    }
}

For a project that I was using Thymeleaf in, I have the following code which shows the login page stored in resources/templates folder.

@Controller
public class LoginController {

    @GetMapping("/login")
    public String showLoginForm() {
        return "login"; //note that this is just the name of the file with no extension
    }
}

Be sure to put the html file in the correct folder. My guess is that since you’re using Thymeleaf, you will probably be using some templates.

11 People found this is helpful
Advertisement