View on GitHub

reading-notes

Spring Boot:

Spring Boot is an open source Java-based framework used to create a micro Service.

Serving Web Content with Spring MVC:

Make create a “Hello, World” web site with Spring.

After doing the steps you will be able to run web site on: http://localhost:8080/

To start from scratch:

If you use Gradle, visit the Spring Initializr https://start.spring.io/ to generate a new project with the required dependencies (Spring Web, Thymeleaf, and Spring Boot DevTools).
Manual Initialization (optional)

Create a Web Controller

identify the controller by the @Controller annotation
package com.example.servingwebcontent;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

	@GetMapping("/greeting")
	public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
		model.addAttribute("name", name);
		return "greeting";
	}

}

The @GetMapping annotation ensures that HTTP GET requests to /greeting are mapped to the greeting() method.

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method.

Spring MVC and Thymeleaf: how to access data from templates

Spring model attributes

Add attribute to Model via its addAttribute method:

    @RequestMapping(value = "message", method = RequestMethod.GET)
        public String messages(Model model) {
            model.addAttribute("messages", messageRepository.findAll());
            return "message/list";
        }
    @RequestMapping(value = "message", method = RequestMethod.GET)
        public ModelAndView messages() {
            ModelAndView mav = new ModelAndView("message/list");
            mav.addObject("messages", messageRepository.findAll());
            return mav;
        }
    @ModelAttribute("messages")
        public List<Message> messages() {
            return messageRepository.findAll();
        }