freemarker springboot ModelAndView
时间: 2023-12-18 20:05:21 浏览: 78
Freemarker is a template engine that allows you to generate dynamic HTML pages. Spring Boot is a framework that simplifies the development of web applications by providing pre-configured settings and dependencies. ModelAndView is a class in Spring Boot that represents a model and view, used to pass data to a view and specify the view to be rendered.
To use Freemarker with Spring Boot, you need to add the following dependencies to your project:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
```
Next, you can create a controller class with a request mapping that returns a ModelAndView object:
```
@Controller
public class MyController {
@RequestMapping("/myPage")
public ModelAndView myPage() {
ModelAndView modelAndView = new ModelAndView("myPage");
modelAndView.addObject("message", "Hello World!");
return modelAndView;
}
}
```
In this example, the "myPage" template is used to render the view, and the "message" object is passed as a parameter to the template. The "message" object can be accessed in the template using the syntax ${message}.
Finally, you need to create the "myPage" template in the "templates" directory of your application. Here's an example of what the template might look like:
```
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
```
When the /myPage endpoint is accessed, Spring Boot will render the "myPage" template with the "Hello World!" message.
阅读全文