skip to Main Content

I am trying to get the HTML page that I created. This is the structure of my project:

enter image description here

This is the "IndexController" class:

@RestController
@AllArgsConstructor
@RequestMapping(path = "/webpage")
public class IndexController {

        @GetMapping(path = {"mainpage"})
        @ResponseBody
        public String index(){
            return "Index";
        }
    
        @PostMapping("/check")
        public String CheckDataset(@ModelAttribute CheckModel checkModel){
            System.out.println(checkModel);
            return null;
        }
    
    }

When I open the HTML webpage directly from intellij:

enter image description here

Is opening perfectly, but when I am trying to open the HTML from Spring Boot is returning just the "Index" String.

Do you have any idea how to solve this?

2

Answers


  1. To return the HTML page (view), you have to use Spring MVC, i.e. @Controller instead of @RestController and return ModelAndView with index as a view name:

    @Controller
    @AllArgsConstructor
    @RequestMapping("/webpage")
    public class IndexController {
    
        @GetMapping(path = {"mainpage"})
        public ModelAndView index() {
            final var modelAndView = new ModelAndView();
            modelAndView.setViewName("index");
            return modelAndView;
        }
    
        // other methods
    }
    
    Login or Signup to reply.
  2. Please note that your class IndexController shall not have @RestController if you need to show an HTML page. It shall only have @Controller.

    In simple terms @RestController = @Controller + @ResponseBody

    In your case, the @RestController annotation you used makes all the methods within it @ResponseBody by default, and you don’t have to explicitly mention

    @ResponseBody annotation doesn’t show the view instead it sends a String response.

    Steps to fix this issue:

    1. Change @RestController annotation to @Controller in class level
    2. Remove @ResponseBody from the method in which you’re planning to show the HTML

    So your code will be

    @Controller
    @AllArgsConstructor
    @RequestMapping(path = "/webpage")
    public class IndexController {
    
        @GetMapping(path = {"mainpage"})
        public String index(){
            return "Index";
        }
    
       //Other methods
        
    }
    

    Just make sure you have spring-boot-starter-thymeleaf dependency in your POM.xml

    Thanks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search