一、spring使用thymeleaf做解析器其实很简单,这是基于xml配置的方式

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/tx
  9. http://www.springframework.org/schema/tx/spring-tx.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd
  12. http://www.springframework.org/schema/mvc
  13. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  14. http://www.springframework.org/schema/aop
  15. http://www.springframework.org/schema/aop/spring-aop.xsd">
  16. <context:component-scan base-package="com.test.controller"></context:component-scan>
  17. <!-- 开启mvc注解,可使用@DateTimeFormat,@NumberFormat -->
  18. <mvc:annotation-driven></mvc:annotation-driven>
  19.  
  20. <!-- 告知静态文件不要拦截,直接访问,这种方式下面那种要好在可以访问web-info下的资源 -->
  21. <mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources>
  22. <mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
  23. <mvc:resources location="/WEB-INF/images/" mapping="/images/**"></mvc:resources>
  24.  
  25. <!-- 配置默认servlet静态资源访问 -->
  26. <!-- <mvc:default-servlet-handler/> -->
  27.  
  28. <!-- SpringResourceTemplateResolver automatically integrates with Spring's
  29. own -->
  30. <!-- resource resolution infrastructure, which is highly recommended. -->
  31. <bean id="templateResolver"
  32. class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
  33. <property name="prefix" value="/WEB-INF/templates/" />
  34. <property name="suffix" value=".html" />
  35. <!-- HTML is the default value, added here for the sake of clarity. -->
  36. <property name="templateMode" value="HTML" />
  37. <!-- Template cache is true by default. Set to false if you want -->
  38. <!-- templates to be automatically updated when modified. -->
  39. <property name="cacheable" value="false" />
  1.     <property name="characterEncoding" value="UTF-8"/>
  1. </bean> <!-- SpringTemplateEngine automatically applies SpringStandardDialect and --> <!-- enables Spring's own MessageSource message resolution mechanisms. --> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> <!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed up --> <!-- execution in most scenarios, but might be incompatible with specific --> <!-- cases when expressions in one template are reused across different data --> <!-- ypes, so this flag is "false" by default for safer backwards --> <!-- compatibility. --> <property name="enableSpringELCompiler" value="true" /> </bean> <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <!-- NOTE 'order' and 'viewNames' are optional --> <property name="order" value="1" />
  1. <property name="characterEncoding" value="UTF-8"/>
  1. <!-- Controller中返回的视图名后缀包含leaf的,才会进行解析 --> <!-- <property name="viewNames" value="*leaf" /> --> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsps/" /> <property name="suffix" value=".jsp" /> <property name="order" value="" /> <!-- Controller中返回的视图名后缀包含jsp的,才会进行解析 --> <!-- <property name="viewNames" value="*jsp" /> --> </bean> </beans>

和我们传统的配置文件相比,也就多增加了红色的部分,如果你的项目不会使用到jsp,那么就没有必要再配置jsp的解析器了

二、基于注解的配置,首先这个web.xml需要改动成下面这个样子

  1. <?xml version="1.0" encoding="utf-8"?>
  2.  
  3. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  5. http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  6. version="3.1" metadata-complete="true">
  7.  
  8. <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
  9. instead of the default XmlWebApplicationContext -->
  10. <context-param>
  11. <param-name>contextClass</param-name>
  12. <param-value>
  13. org.springframework.web.context.support.AnnotationConfigWebApplicationContext
  14. </param-value>
  15. </context-param>
  16.  
  17. <!-- Configuration locations must consist of one or more comma- or space-delimited
  18. fully-qualified @Configuration classes. Fully-qualified packages may also be
  19. specified for component-scanning -->
  20. <context-param>
  21. <param-name>contextConfigLocation</param-name>
  22. <param-value>com.test.dao.configure.ApplicationConfigure</param-value>
  23. </context-param>
  24.  
  25. <listener>
  26. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27. </listener>
  28.  
  29. <servlet>
  30. <servlet-name>springMVC</servlet-name>
  31. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  32. <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
  33. instead of the default XmlWebApplicationContext -->
  34. <init-param>
  35. <param-name>contextClass</param-name>
  36. <param-value>
  37. org.springframework.web.context.support.AnnotationConfigWebApplicationContext
  38. </param-value>
  39. </init-param>
  40. <!-- Again, config locations must consist of one or more comma-(逗号) or space-delimited(空格)
  41. and fully-qualified @Configuration classes -->
  42. <init-param>
  43. <param-name>contextConfigLocation</param-name>
  44. <param-value>com.test.mvc.configure.SpringWebConfig</param-value>
  45. </init-param>
  46. <load-on-startup></load-on-startup>
  47. </servlet>
  48. <servlet-mapping>
  49. <servlet-name>springMVC</servlet-name>
  50. <url-pattern>/</url-pattern>
  51. </servlet-mapping>
  52. <filter>
  53. <filter-name>characterEncodingFilter</filter-name>
  54. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  55. <init-param>
  56. <param-name>encoding</param-name>
  57. <param-value>UTF-</param-value>
  58. </init-param>
  59. <init-param>
  60. <param-name>forceEncoding</param-name>
  61. <param-value>true</param-value>
  62. </init-param>
  63. </filter>
  64. <filter-mapping>
  65. <filter-name>characterEncodingFilter</filter-name>
  66. <url-pattern>/*</url-pattern>
  67. </filter-mapping>
  68.  
  69. </web-app>

标红部分就是与传统web.xml配置的区别。

下面是声明thymeleaf的java配置方式

  1. package com.test.mvc.configure;
  2.  
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.ComponentScan;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.support.ResourceBundleMessageSource;
  10. import org.springframework.format.FormatterRegistry;
  11. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  12. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  13. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  14. import org.thymeleaf.spring4.SpringTemplateEngine;
  15. import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
  16. import org.thymeleaf.spring4.view.ThymeleafViewResolver;
  17. import org.thymeleaf.templatemode.TemplateMode;
  18.  
  19. import com.test.fomatter.MyDateFormatter;
  20.  
  21. @Configuration
  22. @EnableWebMvc

@ComponentScan(basePackages = { "com.test.controller" }, includeFilters = {
  @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {
            org.springframework.stereotype.Controller.class }) })

  1. public class SpringWebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
  2. private ApplicationContext applicationContext;
  3.  
  4. public SpringWebConfig() {
  5. super();
  6. }
  7.  
  8. public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
  9. this.applicationContext = applicationContext;
  10. }
  11.  
  12. /* ******************************************************************* */
  13. /* GENERAL CONFIGURATION ARTIFACTS */
  14. /* Static Resources, i18n Messages, Formatters (Conversion Service) */
  15. /*配置静态资源,i18n 信息, 格式转换器*/
  16. /* ******************************************************************* */
  17. @Override
  18. public void addResourceHandlers(final ResourceHandlerRegistry registry) {
  19. super.addResourceHandlers(registry);
  20. registry.addResourceHandler("/images/**").addResourceLocations("/images/");
  21. registry.addResourceHandler("/css/**").addResourceLocations("/css/");
  22. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
  23. }
  24.  
  25. @Bean
  26. public ResourceBundleMessageSource messageSource() {
  27. ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
  28. //设置国际化资源的baseName
  29. messageSource.setBasename("Messages");
  30. return messageSource;
  31. }
  32.  
  33. /**
  34. * 添加转换器
  35. */
  36. @Override
  37. public void addFormatters(final FormatterRegistry registry) {
  38. super.addFormatters(registry);
  39. registry.addFormatter(varietyFormatter());
  40. }
  41.  
  42. @Bean
  43. public MyDateFormatter varietyFormatter() {
  44. return new MyDateFormatter("yyyy-MM-dd");
  45. }
  46.  
  47. /* **************************************************************** */
  48. /* THYMELEAF-SPECIFIC ARTIFACTS */
  49. /* TemplateResolver <- TemplateEngine <- ViewResolver */
  50. /* **************************************************************** */
  51. /**
  52. * thymeleaf的模板解析器
  53. * @return
  54. */
  55. @Bean
  56. public SpringResourceTemplateResolver templateResolver() {
  57. // SpringResourceTemplateResolver automatically integrates with Spring's
  58. // own
  59. // resource resolution infrastructure, which is highly recommended.
  60. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
  61. templateResolver.setApplicationContext(this.applicationContext);
  62.  
  63. templateResolver.setPrefix("/WEB-INF/templates/");
  64.  
  65. templateResolver.setSuffix(".html");
  66. // HTML is the default value, added here for the sake of clarity.
  67. //模板解析模式使用HTML模式
  68. templateResolver.setTemplateMode(TemplateMode.HTML);
  69. // Template cache is true by default. Set to false if you want
  70. // templates to be automatically updated when modified.
  71. //是否缓存模板,默认是true,不过在调试的时候最好是false,因为模板随时需要改变
  72. templateResolver.setCacheable(false);
         templateResolver.setCharacterEncoding("utf-8");
  73. return templateResolver;
  74. }
  75.  
  76. /**
  77. * thymeleaf的模板引擎
  78. * @return
  79. */
  80. @Bean
  81. public SpringTemplateEngine templateEngine() {
  82. // SpringTemplateEngine automatically applies SpringStandardDialect and
  83. // enables Spring's own MessageSource message resolution mechanisms.
  84. SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  85. templateEngine.setTemplateResolver(templateResolver());
  86. // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
  87. // speed up execution in most scenarios, but might be incompatible
  88. // with specific cases when expressions in one template are reused
  89. // across different data types, so this flag is "false" by default
  90. // for safer backwards compatibility.
  91. templateEngine.setEnableSpringELCompiler(true);
  92. return templateEngine;
  93. }
  94.  
  95. /**
  96. * thymeleaf的视图解析器
  97. * @return
  98. */
  99. @Bean
  100. public ThymeleafViewResolver viewResolver() {
  101. ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
  102. viewResolver.setTemplateEngine(templateEngine());
  1. templateResolver.setCharacterEncoding("utf-8");
  1.      return viewResolver;
      }
    }

spring使用thymeleaf的更多相关文章

  1. spring boot + thymeleaf 3 国际化

    在给spring boot 1.5.6 + thymeleaf 3进行国际化时,踩了一个坑(其实不止一个). 现象: 看到了吧, 就是取值的key, 后面被加了_en_US 或 _zh_CN, 以及前 ...

  2. spring boot + Thymeleaf开发web项目

    "Spring boot非常适合Web应用程序开发.您可以轻松创建自包含的HTTP应用.web服务器采用嵌入式Tomcat,或者Jetty等.大多数情况下Web应用程序将使用 spring- ...

  3. Spring boot +Spring Security + Thymeleaf 认证失败返回错误信息

    [Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Stat ...

  4. Spring boot+Thymeleaf+easyui集成:js创建组件页面报错

    开发工具:Ideal 使用场景:Demo 前提:       环境:Spring boot +Thymeleaf+easyui 引入thymeleaf模板引擎 <html lang=" ...

  5. spring boot: thymeleaf模板引擎使用

    spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...

  6. Spring MVC + Thymeleaf

    参考网址: https://www.cnblogs.com/litblank/p/7988689.html 一.简介 1.Thymeleaf 在有网络和无网络的环境下皆可运行,而且完全不需启动WEB应 ...

  7. Spring Boot Thymeleaf 实现国际化

    开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了.SpringBoot支持如下页面模板语言 Thymeleaf FreeMarker Vel ...

  8. 图书-技术-SpringBoot:《Spring Boot2 + Thymeleaf 企业应用实战》

    ylbtech-图书-技术-SpringBoot:<Spring Boot2 + Thymeleaf 企业应用实战> <Spring Boot 2+Thymeleaf企业应用实战&g ...

  9. spring boot + thymeleaf 乱码问题

    spring boot + thymeleaf 乱码问题 hellotrms 发布于 2017/01/17 15:27 阅读 1K+ 收藏 0 答案 1 开发四年只会写业务代码,分布式高并发都不会还做 ...

随机推荐

  1. 【LEETCODE】32、LeetCode的第35题,查找插入的位置

    凉凉,看来想做好一个题还不容易啊... 有点难受... 1.看看题目吧 Given a sorted array and a target value, return the index if the ...

  2. Django之forms组件进阶

    Django Form表单组件   Form介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要 ...

  3. Centos7 fstab盘符挂载硬盘导致重启系统失败解决办法

    服务器拥有多个硬盘插槽,在进行维护或重启时,这些硬盘的相对位置可能发生变化.利用盘符(dev/vda)方式挂载磁盘,可能由于磁盘顺序变化导致重启时读取fstab文件发生错误,从而无法正常重启服务器. ...

  4. java源码解析之String类(五)

    /* * 切片函数,非常重要,这里一定要牢记beginIndex是开始位置,endIndex是结束位置,区别于以前学的offset是开始位置,而count或length是个数和长度 * 比如说,new ...

  5. tar 命令参数解释

    tar 命令 tar [-cxtzjvfpPN]文件与目录参数说明:-c :建立一个打包文件:-x :解开一个打包文件:-t :查看 tar包里面的文件:(特别注意,在选择参数时,c/x/t仅能存在一 ...

  6. redis安装与php安装redis模块

    一.安装redis 1.下载 wget https://github.com/antirez/redis/archive/2.8.23.tar.gz 2.解压缩 tar -zxvf 2.8.23.ta ...

  7. 【半小时大话.net依赖注入】(一)理论基础+实战控制台程序实现AutoFac注入

    系列目录 第一章|理论基础+实战控制台程序实现AutoFac注入 第二章|AutoFac的常见使用套路 第三章|实战Asp.Net Framework Web程序实现AutoFac注入 第四章|实战A ...

  8. Disruptor 详解 一

    这篇博客将主要通过几个示例,简单讲述 Disruptor 的使用方法: 一.disruptor 简介 Disruptor 是英国外汇交易公司 LMAX 开发的一个无锁高性能的线程间消息传递的框架.目前 ...

  9. ECharts 地图绘制与钻取简易接口

    1.地图绘制过程原理 给定范围边界经纬度数据,再给它个名字就构成了绘制地图的基础.也就是说,你可以绘制任意形状的地图版块. 2.地图数据生成 中国以及省市县等地图的基础数据可以从这里生成与下载. ht ...

  10. [深度学习]TensorFlow安装

    virtualenv 可以用来建立一个专属于项目的python环境,保持一个干净的环境.只需要通过命令创建一个虚拟环境,不用的时候通过命令退出,删除.实践证明用虚拟环境能避免很多糟心的事. 下面介绍一 ...