spring使用thymeleaf
一、spring使用thymeleaf做解析器其实很简单,这是基于xml配置的方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.test.controller"></context:component-scan>
<!-- 开启mvc注解,可使用@DateTimeFormat,@NumberFormat -->
<mvc:annotation-driven></mvc:annotation-driven> <!-- 告知静态文件不要拦截,直接访问,这种方式下面那种要好在可以访问web-info下的资源 -->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/WEB-INF/images/" mapping="/images/**"></mvc:resources> <!-- 配置默认servlet静态资源访问 -->
<!-- <mvc:default-servlet-handler/> --> <!-- SpringResourceTemplateResolver automatically integrates with Spring's
own -->
<!-- resource resolution infrastructure, which is highly recommended. -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<!-- HTML is the default value, added here for the sake of clarity. -->
<property name="templateMode" value="HTML" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="false" />
<property name="characterEncoding" value="UTF-8"/>
</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" />
<property name="characterEncoding" value="UTF-8"/>
<!-- 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需要改动成下面这个样子
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true"> <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param> <!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also be
specified for component-scanning -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.test.dao.configure.ApplicationConfigure</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<!-- Again, config locations must consist of one or more comma-(逗号) or space-delimited(空格)
and fully-qualified @Configuration classes -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.test.mvc.configure.SpringWebConfig</param-value>
</init-param>
<load-on-startup></load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
标红部分就是与传统web.xml配置的区别。
下面是声明thymeleaf的java配置方式
package com.test.mvc.configure; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode; import com.test.fomatter.MyDateFormatter; @Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.test.controller" }, includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {
org.springframework.stereotype.Controller.class }) })
public class SpringWebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext; public SpringWebConfig() {
super();
} public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
} /* ******************************************************************* */
/* GENERAL CONFIGURATION ARTIFACTS */
/* Static Resources, i18n Messages, Formatters (Conversion Service) */
/*配置静态资源,i18n 信息, 格式转换器*/
/* ******************************************************************* */
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
} @Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
//设置国际化资源的baseName
messageSource.setBasename("Messages");
return messageSource;
} /**
* 添加转换器
*/
@Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatter(varietyFormatter());
} @Bean
public MyDateFormatter varietyFormatter() {
return new MyDateFormatter("yyyy-MM-dd");
} /* **************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS */
/* TemplateResolver <- TemplateEngine <- ViewResolver */
/* **************************************************************** */
/**
* thymeleaf的模板解析器
* @return
*/
@Bean
public SpringResourceTemplateResolver templateResolver() {
// SpringResourceTemplateResolver automatically integrates with Spring's
// own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
//模板解析模式使用HTML模式
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
//是否缓存模板,默认是true,不过在调试的时候最好是false,因为模板随时需要改变
templateResolver.setCacheable(false);
templateResolver.setCharacterEncoding("utf-8");
return templateResolver;
} /**
* thymeleaf的模板引擎
* @return
*/
@Bean
public SpringTemplateEngine templateEngine() {
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(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 types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
} /**
* thymeleaf的视图解析器
* @return
*/
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
templateResolver.setCharacterEncoding("utf-8");
return viewResolver;
}
}
spring使用thymeleaf的更多相关文章
- spring boot + thymeleaf 3 国际化
在给spring boot 1.5.6 + thymeleaf 3进行国际化时,踩了一个坑(其实不止一个). 现象: 看到了吧, 就是取值的key, 后面被加了_en_US 或 _zh_CN, 以及前 ...
- spring boot + Thymeleaf开发web项目
"Spring boot非常适合Web应用程序开发.您可以轻松创建自包含的HTTP应用.web服务器采用嵌入式Tomcat,或者Jetty等.大多数情况下Web应用程序将使用 spring- ...
- Spring boot +Spring Security + Thymeleaf 认证失败返回错误信息
[Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Stat ...
- Spring boot+Thymeleaf+easyui集成:js创建组件页面报错
开发工具:Ideal 使用场景:Demo 前提: 环境:Spring boot +Thymeleaf+easyui 引入thymeleaf模板引擎 <html lang=" ...
- spring boot: thymeleaf模板引擎使用
spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...
- Spring MVC + Thymeleaf
参考网址: https://www.cnblogs.com/litblank/p/7988689.html 一.简介 1.Thymeleaf 在有网络和无网络的环境下皆可运行,而且完全不需启动WEB应 ...
- Spring Boot Thymeleaf 实现国际化
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了.SpringBoot支持如下页面模板语言 Thymeleaf FreeMarker Vel ...
- 图书-技术-SpringBoot:《Spring Boot2 + Thymeleaf 企业应用实战》
ylbtech-图书-技术-SpringBoot:<Spring Boot2 + Thymeleaf 企业应用实战> <Spring Boot 2+Thymeleaf企业应用实战&g ...
- spring boot + thymeleaf 乱码问题
spring boot + thymeleaf 乱码问题 hellotrms 发布于 2017/01/17 15:27 阅读 1K+ 收藏 0 答案 1 开发四年只会写业务代码,分布式高并发都不会还做 ...
随机推荐
- 音视频技术“塔尖”之争,网易云信如何C位出道?
音视频技术“塔尖”之争,网易云信如何C位出道? 社交+美颜.抖音短视频.在线狼人杀.直播竞答.子弹短信……,过往两三年间,互联网新产品和新玩法层出不穷,风口不断切换.这些爆红的网络应用背后,都有一些共 ...
- 【设计模式】行为型02模板方法模式(Template Method Patten)
五一长假,没有出去,不喜欢嘈杂的人群,玩了会游戏发泄了下憋在心底的戾气,手旁大马克杯里是母亲泡的绿茶.点开自己的播放列表,耳机里传来的是理查德克莱德曼的致爱丽丝.自己是个凡人,卑微渺小的活着.不说废话 ...
- ubuntu16.04基本设置
1. ubuntu16.04开启ssh https://jingyan.baidu.com/article/f54ae2fc6f9eef1e93b8497a.html 2. windows 远程桌面连 ...
- java 获取客户端的ip地址
import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHo ...
- HDU 6011:Lotus and Characters(贪心)
http://acm.hdu.edu.cn/showproblem.php?pid=6011 题意:共有n种字符,每种字符有一个val和一个cnt,代表这个字符的价值和数量.可以制造的总价值是:第一个 ...
- Larave使用composer安装无反应,提示“Changed current directory to C:/Users/Administrator/AppData/Roaming/Composer”
按照Laravel文档的安装方式在windows上安装Laravel时,执行composer global require "laravel/installer". 然后命令行就显 ...
- c++ 函数知识点汇总
c++ 函数知识点汇总 swap函数 交换两个数组元素 比如 swap(a[i],a[j]); 就是交换a[i] 和 a[j] 的值 strcpy() 复制一个数组元素的值到另一个数组元素里 strc ...
- JVM中有哪些内存区域,分别是用来干什么的
前言 之前我们探讨过一个.class文件是如何被加载到jvm中的.但是jvm内又是如何划分内存的呢?这个内被加载到了那一块内存中?jvm内存划分也是面试当中必被问到的一个面试题. 什么是jvm内存区域 ...
- Linux部署项目常用命令
前言:一般项目都会使用阿里云等服务器作为云服务器.此时必不可免会使用到一系列常用的命令.这里我整合一下常用的命令 1.一般链接阿里云服务器常用的的是xshell跟xftp. 下载路径:https:// ...
- [译]试用新的System.Text.Json API
译注 可能有的小伙伴已经知道了,在.NET Core 3.0中微软加入了对JSON的内置支持. 一直以来.NET开发者们已经习惯使用Json.NET这个强大的库来处理JSON. 那么.NET为什么要增 ...