Show List

Working with controllers and views in Spring Boot

In Spring Boot, controllers and views are used to handle incoming requests and generate dynamic web pages, respectively.

Controllers are the components in Spring MVC that handle HTTP requests and generate the response. They are defined as classes annotated with @Controller and contain methods annotated with @RequestMapping to handle specific requests.

For example, to define a simple controller that maps to the root URL:

@Controller
public class MyController {

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

Views in Spring Boot are typically HTML templates that are rendered to generate the final web page. There are various template engines that you can use with Spring Boot, such as Thymeleaf, FreeMarker, and more.

For example, to create a simple Thymeleaf template for the "home" view:

<!DOCTYPE html>
<html>
  <head>
    <title>Home Page</title>
  </head>
  <body>
    <h1>Welcome to the Home Page</h1>
  </body>
</html>

In the example above, the home string returned from the controller method maps to the home.html Thymeleaf template, which will be rendered to generate the final HTML page that is returned to the client.

By using controllers and views, you can separate the logic for handling incoming requests and generating the response from the presentation of the data, making it easier to maintain and test your application.


    Leave a Comment


  • captcha text