Riyash.D
Riyash.D

Reputation: 69

How to return html from Rest API with spring boot application

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";
    }

Upvotes: 4

Views: 7738

Answers (5)

Pramuditha
Pramuditha

Reputation: 728

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.

Upvotes: 0

so-random-dude
so-random-dude

Reputation: 16465

@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.

Upvotes: 0

egorlitvinenko
egorlitvinenko

Reputation: 2776

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.

Upvotes: 3

Holger Ludvigsen
Holger Ludvigsen

Reputation: 2546

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();

Upvotes: 0

Plog
Plog

Reputation: 9622

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.

Upvotes: 0

Related Questions