Spring MVC 5 + Thymeleaf 注解配置
Spring的配置方式一般为两种:XML配置和注解配置
Spring从3.0开始以后,推荐使用注解配置,这两种配置的优缺点说的人很多,我就不说了,自行体会,下面就用注解配置实现一个Spring MVC Web Demo
先看看项目结构:
可以看到没有任何XML配置文件,全都是Java代码实现。
使用 Maven 新建一个项目,当然你用IEDA,Eclipse新建一个空的项目一样的,然后添加依赖,依赖下面直接给出:
4.0.0
spring-mvc
spring-mvc
1.0-SNAPSHOT
war<name>Spring-mvc Maven Webapp</name><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><failOnMissingWebXml>false</failOnMissingWebXml><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><spring.version>5.0.6.RELEASE</spring.version><thymeleaf.version>3.0.9.RELEASE</thymeleaf.version></properties><dependencies><!--spring相关包--><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><!--j2ee相关包 servlet、jsp、jstl--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId><version>${thymeleaf.version}</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--jackson--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.5</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!--配置热启动--><configuration><fork>true</fork></configuration></plugin><!--servlet容器 tomcat 插件--><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version></plugin></plugins></build> </project>
新建 MvcWebConfig 配置类 实现WebMvcConfigurer接口,重写configureViewResolvers 方法即可,并且使用 @Configuration、@ComponentScan 注解 MvcWebConfig 类,下面我给出主要代码,然后说明代码的作用。
/*** STEP 1 - 创建模版解析器*/@Beanpublic ITemplateResolver templateResolver() {SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();templateResolver.setApplicationContext(applicationContext);templateResolver.setPrefix("/WEB-INF/templates/");templateResolver.setSuffix(".html");templateResolver.setCharacterEncoding("UTF-8");templateResolver.setTemplateMode(TemplateMode.HTML);templateResolver.setCacheable(false);return templateResolver;}/*** STEP 2 - 创建模版引擎* 并为模板引擎注入模板解析器*/@Beanpublic SpringTemplateEngine templateEngine() {SpringTemplateEngine templateEngine = new SpringTemplateEngine();templateEngine.setTemplateResolver(templateResolver());templateEngine.setEnableSpringELCompiler(true);return templateEngine;}/*** STEP 3 - 注册 Thymeleaf 视图解析器* 并为解析器注入模板引擎*/@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();viewResolver.setTemplateEngine(templateEngine());viewResolver.setCharacterEncoding("UTF-8");registry.viewResolver(viewResolver);}
- templateResolver 方法和XML配置的类似
- 中文会有乱码问题,需要设置 "UTF-8",两个地方必须都要设置,否则会显示乱码
新建 MvcWebAppInitializer 类 extends 抽象类 AbstractAnnotationConfigDispatcherServletInitializer,重写以下几个方法
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{MvcWebConfig.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();encodingFilter.setEncoding("UTF-8");encodingFilter.setForceRequestEncoding(true);return new Filter[]{encodingFilter};}
至此,配置已经全部完成。
- 新建 HomeController ,新建 index 视图先看看,能不能跑起来
- index :
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "index";
} - 在 \WEB-INF\templates 目录下新建页面 index.html,并使用thymeleaf 模板引擎
- index :
<!DOCTYPE html><html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Spring Index</title><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous"></head><body><div class="container" style="margin-top: 40px;"><div class="jumbotron"><h1>Spring Mvc 5 + Thymeleaf</h1><p>出现此页面,说明配置成功,弃用xml配置,使用注解方式实现</p><p>mvn tomcat7:run</p><p><a class="btn btn-primary btn-lg" th:href="@{/home/user}" role="button">Learn more</a></p></div></div><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" crossorigin="anonymous"></script><script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script></body></html>
/home/user 页面如下:
至此页面已经完成,现在使用Maven 跑一下,命令:mvn tomcat7:run
当然你也可以用IDEA 的 Edit Configurations 新建一个Maven,如下图:
看一下效果:
没有使用任何XML文件,Spring MVC跑起来了,再试试返回json数据
在 HomeController 新建userList 方法,返回List数组
@ResponseBody
@RequestMapping(value = "/home/userList", method = RequestMethod.GET)
public List userList() {
List userList = new ArrayList<>();
userList.add(new UserInfo(1001, "龙傲天", 23, "成都省"));
userList.add(new UserInfo(1002, "曹孟德", 33, "河北市"));
userList.add(new UserInfo(1003, "Chris", 32, "高新市"));
userList.add(new UserInfo(1003, "Evans", 17, "绵阳市"));return userList;}
- Spring 返回 json数据 直接使用 @ResponseBody 注解杰克
- @ResponseBody 依赖 com.fasterxml.jackson
看下返回json数据的效果
没有使用任何XML文件,实现了一个Web 程序。
Ps:博客园的这个markdown 编辑器有问题,我用Typora写好了复制过来,总有些问题,将就着看吧