How to return html from Rest API with spring boot application

Viewed 6376

I need to return an html page from Rest API in Spring boot Application. The html "test.html" is in src/main/resource directory. Below is my code snippet

    @RequestMapping(value ="/get/getReportById",method = RequestMethod.GET)
    @ResponseBody()
    public String getReportsByCategory(String id) throws Exception{

        try{
        //Do something

        }catch(Exception e){
            e.printStackTrace();
        }


        return "test";
    }
5 Answers

Class should be @Controller, remove @ResponseBody, you also should have configured template processor (Thymeleaf, for example).

Update

If you look inside code of @RestController, you will see that it is composition from @Controller and @ResponseBody annotations. So ResponseBody would be automatically applied to all methods.

If you want to return a view you do not want to have your controller method annotated as a @ResponseBody so remove that and it should work.

You need to read test.html from classpath and return it as a string:

InputStream htmlStream = getClass().getResourceAsStream("test.html");
return new Scanner(htmlStream, "UTF-8").useDelimiter("\\A").next();

@RestController

is to deal with webservices, it is all about data, presentation markup such as HTML doesn't have any role here.

@Controller

This is what you want to use if there is a view involved. view can be anything which will spit out an html (with or without interpolating the model). You can use good old JSP, JSF or templating engines like thymeleaf, velocity, freemarker etc.

You can use ModelAndView to view HTML page as follows,

 @RequestMapping(value ="/get/getReportById")
 public ModelAndView getReportsByCategory() throws Exception{

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test.html");
    return modelAndView;

 }

Import library,

import org.springframework.web.servlet.ModelAndView;

This test.html file should be inside the src/main/resource/static/ directory.

Related