Wie kann ich eine HTML-Seite von einem RESTful-Controller in Spring Boot zurückgeben?

Lesezeit: 5 Minuten

Gustavos Benutzeravatar
Gustavo

Ich möchte eine einfache HTML-Seite von einem Controller zurückgeben, erhalte jedoch nur den Namen der Datei, nicht deren Inhalt. Warum?

Das ist mein Controller-Code:

@RestController
public class HomeController {

    @RequestMapping("/")
    public String welcome() {
        return "login";
    }
}

Das ist meine Projektstruktur:

[enter image description here

  • try to add a servlet to direct to index.html @ServletComponentScan then add @WebSevlet(urlPatterns = “”) MainIndex

    – meadlai

    Mar 5, 2020 at 23:43

kukkuz's user avatar
kukkuz

When using @RestController like this:

@RestController
public class HomeController {

    @RequestMapping("https://stackoverflow.com/")
    public String welcome() {
        return "login";
    }
}

This is the same as you do like this in a normal controller:

@Controller
public class HomeController {

    @RequestMapping("https://stackoverflow.com/")
    @ResponseBody
    public String welcome() {
        return "login";
    }
}

Using @ResponseBody returns return "login"; as a String object. Any object you return will be attached as payload in the HTTP body as JSON.

This is why you are getting just login in the response.

  • I am confused. What is the problem and how to fix ?

    – Itération 122442

    Aug 19, 2020 at 9:36

  • @Itération122442 You should use Controller annotation for the class and you should remove the ResponseBody annotation from method named welcome()

    – Simone Colnaghi

    Dec 29, 2021 at 21:10

  • lol i do not get why this is marked as correct, it does not tell the answer it just explains the problem

    – Tinovimba Mawoyo

    Mar 15, 2022 at 14:09

Chandan Kumar's user avatar
Chandan Kumar

Follow below steps:

  1. Must put the html files in resources/templates/

  2. Replace the @RestController with @Controller

  3. Remove if you are using any view resolvers.

  4. Your controller method should return file name of view without extension like return "index"

  5. Include the below dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>`
    

  • After adding spring-boot-starter-thymeleaf dependency, the view was resolved

    – Mithilesh Tipkari

    Feb 25, 2020 at 17:53

  • With just spring-starter-web dependency I was able to serve html pages located inside src/main/resources/static , by typing localhost: 8080/helloworld.html( the entire name). But using thmleaf it automatically maps to the html files. SO MY QUESTION is there any option to serve the files through rest end points by just including spring-starter-web dependency

    – Arpan Banerjee

    Apr 9, 2021 at 7:05


  • Using @Controller solved the issue and returned the view as opposed to a string

    – smac2020

    Jul 1, 2021 at 15:10

Happy Nguyen's user avatar
Happy Nguyen

You can try using ModelAndView:

@RequestMapping("https://stackoverflow.com/")
public ModelAndView index () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("index");
    return modelAndView;
}

@kukkuz pretty much answered to the question ‘why?’. For those who are still looking into ‘how’, accumulating what others have answered.

Using a RestController:

@RestController
public class MyRestController {
    @RequestMapping("/")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login.html");
        return modelAndView;
    }  
}
  • pay attention that view name is: ‘login.html’ (full file name).
  • also it is important where the file is located, by default login.html must be in resources/static or resources/public

You may set up an application parameter for a default suffix like:

 spring.mvc.view.suffix=.html

in this case view name must be without extension like ‘login’.

Some suggested thymeleaf can be used.
means you have in your pom.xml dependencies something like this:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
  <version>2.4.4</version>
</dependency>

In that scenario login.html by default must sit in: resources/templates folder, and the call is similar only difference now is in a view name, since .html is used by tymeleaf as a default value.

//  fails by default
//  NO fail if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html
//  NO fail if thymeleaf is added, and there is a file login.html in a resources/templates folder.
@RequestMapping("/loginTest")
public ModelAndView loginTest () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("login");
    return modelAndView;
}

Using a Controller:

@Controller
public class MyController {

  //gets html from a default 'resources/public' or 'resources/static' folder
  @RequestMapping(path="/welcome")
  public String getWelcomePage(){
      return "login.html";
  }

  //gets html from a default 'resources/public' or 'resources/static' folder
  @RequestMapping("/welcome1")
  public ModelAndView getWelcomePageAsModel() {
      ModelAndView modelAndView = new ModelAndView();
      modelAndView.setViewName("login.html");
      return modelAndView;
  }

  //  fails with 404 resource not found by default
  //  NO fail, if spring mvc view suffix is set in properties e.g.: spring.mvc.view.suffix=.html
  //  NO fail, if thymeleaf is added, and there is a file login.html in a resources/templates folder
  @RequestMapping(path="/welcome2")
  public String thisFails(){
      return "login";
  }
}

Prasad's user avatar
Prasad

Replace @Restcontroller with @controller. @Restcontroller returns only content not html and jsp pages.

Davide Calarco's user avatar
Davide Calarco

I did three things:

  • Put the HTML page in {project.basedir}/resources/static/myPage.html;
  • Switch @RestController to @Controller;
  • This is my controller:
@RequestMapping(method = RequestMethod.GET, value = "/")
public String aName() {
    return "myPage.html";
}

No particular dependency is needed.

PGMacDesign's user avatar
PGMacDesign

The answer from Kukkuz did not work for me until I added in this dependency into the pom file:

<!-- Spring boot Thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

From the guide here.

As well as updating the registry resources as outlined here.

It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz’s answer and see if that makes a difference.

1454010cookie-checkWie kann ich eine HTML-Seite von einem RESTful-Controller in Spring Boot zurückgeben?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy