Spring Boot? Render a Web view using the Thymeleaf template engine

Source: Internet
Author: User
Tags uuid spring boot tutorial

Static resource access

When we develop Web applications, we need to reference a large number of JS, CSS, pictures and other static resources.

Default configuration

Spring boot defaults to provide a static resource directory location to be placed under Classpath, and the directory name must conform to the following rules:

    • /static
    • /public
    • /resources
    • /meta-inf/resources

Example: We can create in the src/main/resources/ directory static , place a picture file in that location. After you start the program, try to access it http://localhost:8080/D.jpg . If you can display the picture, the configuration is successful.

Rendering Web pages

In the previous example, we handled the request through @restcontroller, so the content returned was a JSON object. So how do you do it if you need to render an HTML page?

Template engine

Spring boot is still perfect for dynamic HTML implementations and provides the default configuration support for a variety of template engines, so under the recommended template engine, we can quickly get started with developing dynamic websites.

Spring Boot provides the default configuration of the template engine mainly in the following ways:

    • Thymeleaf
    • Freemarker
    • Velocity
    • Groovy
    • Mustache

Spring boot recommends using these template engines to avoid using JSPs, and if you must use JSP, you will not be able to implement many of the features of spring boot, as described later: support for JSP configuration

When you use any of the above template engines, their default template configuration path is: src/main/resources/templates . Of course, you can modify the path, how to modify, in the subsequent template engine configuration properties to query and modify.

Thymeleaf

Thymeleaf is a XML/XHTML/HTML5 template engine that can be used for application development in Web and non-web environments. It is an open source Java library, created by Daniel Fernández, based on the Apache License 2.0 license, and is the author of the Java Cryptographic Library Jasypt.

Thymeleaf provides an optional module for integrating Spring MVC, where you can use Thymeleaf to completely replace JSP or other template engines, such as velocity, freemarker, and so on. The main goal of Thymeleaf is to provide a well-formed template creation that can be properly displayed by the browser, so it can also be used as a static model. You can use it to create validated XML and HTML templates. Rather than writing logic or code, developers simply add tag attributes to the template. Next, these tag properties perform pre-established logic on the DOM (Document Object model).

Sample Template:

<table>  <thead>    <tr>      <th th:text= "#{msgs.headers.name}" >Name</td>      <th th:text= "#{msgs.headers.price}" >Price</td>    </tr>  </thead>  < tbody>    <tr th:each= "prod: ${allproducts}" >      <td th:text= "${prod.name}" >Oranges</td>      <td th:text= "${#numbers. Formatdecimal (prod.price,1,2)}" >0.99</td>    </tr>  </ Tbody></table>

  

You can see that thymeleaf is mainly attributed to the HTML tag, the browser when parsing the HTML, when the detection of the attributes are ignored, so the thymeleaf template can be opened directly through the browser display, which is very conducive to the separation of the front and back.

To use Thymeleaf in spring boot, simply introduce the following dependencies and src/main/resources/templates write the template file under the default template path.

<dependency><groupId>org.springframework.boot</groupId><artifactId> Spring-boot-starter-thymeleaf</artifactid></dependency>

  

Pom.xml

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apache . org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.wls</groupid > <artifactId>project</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging> jar</packaging> <name>project</name> <description>project</description> <parent&        Gt <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-parent</  Artifactid> <version>1.5.6.RELEASE</version> <relativePath/> <!--lookup parent from Repository-</parent> <properties> <project.build.sourceencoding>utf-8</project.b Uild.sourceencoding> <projEct.reporting.outputencoding>utf-8</project.reporting.outputencoding> <java.version>1.8</ java.version> </properties> <dependencies> <dependency> <groupid>org.sp Ringframework.boot</groupid> <artifactId>spring-boot-starter</artifactId> </depende ncy> <dependency> <groupId>org.springframework.boot</groupId> <artifa ctid>spring-boot-starter-web</artifactid> </dependency> <dependency> <gro            Upid>org.springframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mybatis Dependent-<dependenc Y> <groupId>org.mybatis.spring.boot</groupId> <artifactid>mybatis-spring-boot-s       Tarter</artifactid>     <version>1.1.1</version> </dependency> <!--MySQL Drive-&LT;DEPENDENCY&G            T <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-jdbc</artifact            id> </dependency> <dependency> <groupId>org.apache.tomcat</groupId>            <artifactId>tomcat-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <! --<version>5.1.21</version>--> </dependency> < dependency!--JSON library-<dependen            Cy> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.43</version> </dependency> <!--JPA--<depend  Ency>          <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-DATA-JP a</artifactid> </dependency> <dependency> <groupid>com.alibaba</groupi d> <artifactId>druid</artifactId> <version>1.1.2</version> </de Pendency> <!--devtools-<dependency> <groupid>org.springframew Ork.boot</groupid> <artifactId>spring-boot-devtools</artifactId> <optional>t            Rue</optional> </dependency> <!--mysql---<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> &LT;/DEP Endency> <!--AOP--<dependency> <groupid>org.springframework.bo      Ot</groupid>      <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--Redis -<!--<dependency> <groupId>org.springframework.boot</groupId> &L T;artifactid>spring-boot-starter-data-redis</artifactid> </dependency>--> &LT;DEPENDENCY&G            T <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPRING-BOOT-STARTER-REDIS&LT;/ARTIFAC            tid> <version>1.4.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactid>spring-session-data-redis&lt            ;/artifactid> </dependency> <!--activemq--<dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-activemq</ Artifactid> </dependency> <!--thymeleaf--<dependency> <grou Pid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid&        Gt </dependency> <!--Mail---<dependency> <groupid>org.sprin Gframework.boot</groupid> <artifactId>spring-boot-starter-mail</artifactId> </depen Dency> <!--swagger2-<dependency> <groupid>io.springfox</gr Oupid> <artifactId>springfox-swagger2</artifactId> &LT;VERSION&GT;2.7.0&LT;/VERSION&G        T </dependency> <dependency> <groupId>io.springfox</groupId> <artifa    Ctid>springfox-swagger-ui</artifactid> <version>2.7.0</version> </dependency>     <dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SP ring-boot-test</artifactid> </dependency> <dependency> <groupId>junit<            /groupid> <artifactId>junit</artifactId> </dependency> <dependency>            <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.10.RELEASE</version> </dependency> </dependencies> <build&gt        ;                <plugins> <plugin> <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactid>mybatis-generator-mave N-plugin</arTifactid> <version>1.3.2</version> <configuration> & Lt;verbose>true</verbose> <overwrite>true</overwrite> </configur ation> </plugin> </plugins> </build></project>

  

Controller

Package com.wls.integrateplugs.hello.controller;/** * Created by WLS on 2017/8/24. */import Java.util.locale;import Java.util.uuid;import Javax.servlet.http.httpsession;import Com.sun.org.apache.regexp.internal.re;import Org.springframework.ui.model;import Org.springframework.ui.ModelMap ; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.restcontroller;import Org.springframework.web.servlet.ModelAndView; Import Springfox.documentation.annotations.ApiIgnore; @RestControllerpublic class Hellocontroller {@RequestMapping ( Value = "/hello", method = requestmethod.get) public String Hello (locale locale, model model) {return "Hello Wor    LD ";    } @RequestMapping ("/helloworld") public String Index () {return ' Hello world '; }/** * When using @restcontroller, use Modelandview to display the page * @param map * @return */@ApiIgnore @RequestMappi Ng (value= "/hellothymeleaf", method = requestmethod.get) Public Modelandview index (Modelmap map) {Modelandview mv = new        Modelandview ("index");        Map.addattribute ("name", "Miss Wang");        Map.addattribute ("Host", "http://blog.didispace.com");    return MV; }/** * Shared session * @param session * @return */@RequestMapping (value = "/uid", method = Requestmetho        D.get) String UID (HttpSession session) {UUID UID = (UUID) session.getattribute ("UID");        if (uid = = null) {uid = Uuid.randomuuid ();        } session.setattribute ("UID", UID);    return Session.getid (); }}

Html

<! DOCTYPE html>

  

As on the page, open the HTML page directly to show Hello World, but after starting the program, access to Http://localhost:8081/project/helloThymeleaf, is to display the controller in the value of host: http://blog.didispace.com , the logical separation of data without destroying the contents of HTML itself.

For more Thymeleaf page syntax, please also visit the THYMELEAF Official document query for use.

Default parameter configuration for Thymeleaf

If you need to modify the default configuration, just copy the following to modify the properties into the application.properties , and modify the required values, such as modifying the template file extension, modify the default template path, and so on.

Application-dev.yml

Spring:datasource:primary:driver-class-name:com.mysql.jdbc.driver # url:jdbc:mysql://192.168.159.128:330    6/mydb url:jdbc:mysql://192.168.223.128:3306/db1 username:wls password:wls141215! Secondary:driver-class-name:com.mysql.jdbc.driver # Url:jdbc:mysql://192.168.159.128:3306/mydb URL:JDBC:  MYSQL://192.168.223.128:3306/DB2 username:wls password:wls141215! Jpa:hibernate:ddl-auto:update show-sql:true thymeleaf:mode:HTML5 encoding:utf-8 content-type: Text/html cache:false prefix:classpath:/templates/suffix:. html check-template-location:true output:a  Nsi:enabled:always mvc:view:prefix:/templates/suffix:. * mail:host:smtp.qq.com Username: [email protected] Password:wls141215sxj properties:mail:smtp:auth:true star Ttls:enable:true required:true redis:database:0# host:192.168.159.128 host:192.168.223.128 port:6379 password:wls141215!      Pool: # Connection pool Maximum number of connections (using negative values for No limit) Max-active:8 # Connection pool maximum blocking wait time (with negative value for No limit) max-wait: 1 # Maximum idle connections in the connection pool MAX-IDLE:8 # Minimum idle connection in connection pool min-idle:0 # connection time-out (ms) timeout:0mybatis:type-aliases-package:com.wls.i  Ntegrateplugs.mybatis.model Mapper-locations:classpath:static/sqlmapper/*.xml check-config-location:true# Config-location:classpath:mybatis/mybatis-config.xmllogging:level:com.wls.shopmall:debugage:18name: Zhang San content: " Name: ${name}, Age: ${age} "CRON:0/3 * * * * * Com.diy.title: pure smile com.diy.description: Sharing life and technology orderinfo:ordernumber:124 5 receiver:wls Province: Beijing City: Beijing area: Daxing District Street: No. 9th Guangping Street Addressdetail: Kyushu Tong Pharmaceutical Co., Ltd. orderstatus:1 Invoicein Fo:invoicetitle: Beijing good pharmacist Big pharmacy Chain Co., Ltd invoicetype:1 details:-orderdetail:productid:1 PRODUCTC ode:bc001 productName: Product 1 unitprice:10.01 count:1#-orderdetail:# productid:2# productcode:bc002# productName: Commodities * unitprice:1 0.01# count:1com.didispace.blog:name: Program ape dd title:spring Boot tutorial desc: ${com.didispace.blog.name} is trying to write "${com." Didispace.blog.title} "# Random string value: ${random.value}# random int number: ${random.int}# random long bignumber: ${random.long}# 10 Random number within Test1: ${random.int (10)}# 10-20 random number test2: ${random.int[10,20]}

Application.yml

Server:  port:8081  context-path:/projectspring:  profiles:    active:dev# Spring.jpa.hibernate.naming.physical-strategy: Org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

  

Support for JSP configuration

Spring boot is not recommended, but if you must use it, you can refer to this project as a scaffold: JSP support

Spring Boot Tutorial Full case

Spring Boot? Render a Web view using the Thymeleaf template engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.