Home > OS >  How to return a html in spring boot controller?
How to return a html in spring boot controller?

Time:12-07

I'm really new to spring boot, this is my first time using it, I don't want to, but I have to, and I'm stuck. I have a spring boot app that displays elements of a database

@GetMapping
public List<Movie> getMovies(){
    return movieService.getMovies();
}

I have this GetMapping, and when I load the page, it displays the element of the database, in JSON format, like this:

[{"id":1,"title":"Django","releaseDate":"2012-12-12","rating":8.4},{"id":2,"title":"Pulp Fiction","releaseDate":"1994-04-13","rating":8.9}]

How should I edit the GetMapping to returnl a html file, in which I display this data? Also, how should I use the html to use the getMovies function?

CodePudding user response:

"Don't want to"? It's a great framework. You'll learn something.

The controller is mapped to a URL with an HTTP request and it returns an HTTP response. Looks like your HTTP client asked for the response as JSON, but it could also ask for plain text or XML.

Your result is correct - this is exactly what Spring controller should be doing.

You need to read a little bit more about Spring web MVC. You can create an HTML page template to render the data in the way you wish.

You could also create a React or Angular front end app that calls the Spring controller and renders the JSON that you got in an HTML page.

Spring web MVC would mean that the page is coupled with the controller as one app.

A React/Angular front end would keep it separate from the controller. You'd have two deployments instead of one.

CodePudding user response:

I recommend using the Thymeleaf view engine for HTML pages if building a Spring MVC application. https://www.thymeleaf.org/documentation.html Maven dependency:

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

Gradle dependency:

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

You can put HTML pages/templates under main/resources/templates. In your controller you can return a ModelAndView (org.springframework.web.servlet.ModelAndView) object. See the doc for available methods.

I highly recommend Spring Boot for web applications, application backends, etc. Saves the tedious configuration of Spring and provides the tools needed to build an enterprise application adhering to industry best practices.

  • Related