简体   繁体   中英

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.

Try replacing the @RequestMapping with @GetMapping("/") or @RequestMapping(value = "/", method = RequestMethod.GET)

Why? because @RequestMapping will map to any request to that URL, so you have to specify that it's a GET request (I suppose that is what you want to use).

Since you didn't share your frontend code that is sending the request we can't tell if there is a problem there. Please share it as well.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM