spring项目如何创建html
时间: 2024-05-16 12:16:04 浏览: 15
视图模板?
要在Spring项目中创建HTML视图模板,需要进行以下步骤:
1. 首先,确保在pom.xml文件(如果您使用的是Maven)或gradle文件(如果您使用的是Gradle)中添加了以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在你的Spring配置类中(通常是一个类上面有 @SpringBootApplication 注解的类),添加如下注解,以启用Thymeleaf视图解析器:
```
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
var resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
var engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
var resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
```
在此示例中,我们启用了Web MVC并配置了一个Thymeleaf视图解析器。我们使用TemplateMode.HTML告诉解析器我们使用的是HTML模板。此配置将 Thymeleaf 视图的前缀设置为/WEB-INF/views/,并将所有的视图文件视为.html文件。
3. 在你的项目中添加一个视图文件夹,其中包含您的HTML视图模板。例如,在您的项目中创建一个名为“views”的文件夹,并在其中添加一个名为“hello.html”的HTML文件,其中包含以下内容:
```
<html>
<head>
<title>Hello</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
```
4. 最后,在Spring控制器类中,您可以使用 @GetMapping 与 @GetMapping("/hello") 注解指向“hello”视图:
```
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
return "hello";
}
}
```
现在,您的Spring项目中已经完成了简单的HTML视图模板的创建。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)