Home > AI > Backend > SpringBoot > spring-web >

ModelAndView

Methods

setViewName()set the current template name,
it should have a html under the resources/templates
addObjectPass attribute or variable(object) to the thymeleaf template

Example

Demo12Application.java

@SpringBootApplication
@RestController
public class Demo12Application {

	public static void main(String[] args) {
		SpringApplication.run(Demo12Application.class, args);
	}



    @RequestMapping("/ok")
    public ModelAndView ok() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("ok");
        modelAndView.addObject("message", "Hello World, Hello Kitty");
        return modelAndView;
    }
}

ok.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
OK
<h1 th:inline="text"> [[${message}]]</h1>
</body>
</html>

Leave a Reply