SpringMvc5整合Thymeleaf-纯注解
一、环境准备
1、整体项目结构
2、pom依赖
<dependencies>
<!--springmvc相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jackson依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.1</version>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--Tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>80</port>
</configuration>
</plugin>
</plugins>
</build>
3、编写实体类Book
public class Book {
private Integer id;
private String type;
private String name;
private String description;
//setter、getter和构造器自行写入
}
4、编写配置类
SpringMvcConfig 类
@Configuration
@ComponentScan("com.lwm.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
ServletConfig 类
/**
* 定义servlet容器启动的配置类,在里面加载spring的配置
*/
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
//加载spring容器配置
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
//加载springmvc容器配置
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {SpringMvcConfig.class};
}
//设置拦截请求,拦截请求归属springmvc处理
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
5、编写Controller
@Controller
@RequestMapping("/books")
public class BookController {
}
此处需要注意,不要使用Rest风格的注解(@RestController
),为什么呢?
要知道一点,@RestController
= @Controller
+ @ResponseBody
,@ResponseBody
的作用是什么?就是设置当前控制器返回值作为响应体。
所以,一旦使用Rest风格的注解,springmvc不会解析该返回值跳转到对应的页面去,页面上显示的一直是return的数据,可以自行测试一番
(PS:
标签:return,templateResolver,class,Thymeleaf,bookList,new,注解,SpringMvc5,public From: https://www.cnblogs.com/qmcx/p/17132764.html