Springboot Starter Training 5 Thymeleaf MVC Project Setup

Posted by jackohara on Sat, 25 Dec 2021 04:16:18 +0100

When we develop the spring boot web project, we need to use JSP for view layer functionality. At this time, we will find a problem. This JSP page is very original and cannot use complex tags. We need to write business code in the most original java+jsp mixed-up way. It is inconvenient to use, and for convenience we need to import third-party tag libraries in JSP to simplify the business code for these view layers. So it's all about importing third-party tag libraries to write code. Why don't we just use the tags in the Thymeleaf template library recommended by spring boot to me to write code? Their function is to do the same thing, labeling==html(jsp page)==business logic in. So to simplify development, we can turn a project into one that uses the Thymeleaf template instead of the cumbersome web pattern.

So now when most spring boot develops web service functionality, we won't choose web + jsp mode, unless we have requirements for compatibility and special functionality.

Thymeleaf mode is simpler to develop than web + jsp mode, and project building is very simple. I highly recommend this mode if I can do it quickly. We use Thymeleaf as a page template and we can use the logical tags that come with Thymeleaf for page development. You can refer to this article for page development.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
   <version>2.2.3.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.11.RELEASE</version>
</dependency>

All example codes Baidu Disk: https://pan.baidu.com/s/1rDpcZtdBA6i7vBmYTMwcUA
Extraction Code: 1234
Database download address Baidu netdisk: https://pan.baidu.com/s/1Q6pbC2SR70HKCeVXgOGUPQ
Extraction Code: 1234
Download mysql51 database

Example Download maven creates the springboot+ThymeleafMVC project. zip
Example Download Common item springboot+ThymeleafMVC item. zip

1 Thymeleaf project structure

Thymeleaf project structure is different from web+jsp project structure. All template html pages are saved in the templates directory, and once they become Thymeleaf template pages, we can use the Thymeleaf tag for business development.

  • Create templates folder template page to save default directory address
  • Create a static folder All static resources save directory addresses (css, js, pictures, html)

Common project structure

Project
   └─src     
      └─templates  
      └─static

maven project

  • Both the resources templates directory and the static directory are in the resources directory
Project
└─src           
   └─main           
      └─ resources 
            └─templates  
            └─static

Static Resource Settings

In application. Set static resources in the YML file. This allows you to use all the static resources in the static file directory.

spring:
  mvc:
    static-path-pattern: /static/**

2 Create Thymeleaf Controller container and html template

Create Controller Container

@Controller
@RequestMapping("/zht")
public class ZhtController {
	@RequestMapping("/index")
	 public String index(Model map,String test) {
		System.out.println("===========Test Accessed===========");
		System.out.println("===========test test value "+test+"===========");
		map.addAttribute("name", "Welcome templates page");
	   return "/index";
	 }
}

**Create an index.html template src/resources/templates/index.html **

The normal project address is src/templates/index.html

<html>
<head>
<meta http-equiv="Content-Type"
      content="text/html; charset=utf-8" />
<title>web page</title>
<link rel="stylesheet" href="../static/css/css.css" />
<style type="text/css">
</style>
</head>
<body th:inline="text">
Welcome[(${name})]
</body>
</html>

Enter in Browser http://localhost:9089/zht/index View effects

3 thymeleaf monomer test

The test content is the same as a web jsp monolithic test.

MyUrlPageTest

@RunWith(SpringRunner.class)
@SpringBootTest(classes=OnApp.class)
@AutoConfigureMockMvc
public class MyUrlPageTest {
	
	@Autowired
	private WebApplicationContext webapp;
	private MockMvc mockMvc;
	@Before
	public void setup() {
        //Enter the spring boot container into the MockMvc container
		mockMvc = MockMvcBuilders.webAppContextSetup(webapp).build();
	}
	@Test
	public void TestPage() throws Exception{
        //Find the Controller container for page control through the url path
        ResultActions results =mockMvc.
            perform(MockMvcRequestBuilders
                    .get("/zht/index").param("test", "Test data from"));
        results.andReturn().getResponse()
            .setCharacterEncoding("UTF-8");
       //View Return Results
        results.
            andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print());
	}
}

test result

===========Test Accessed===========
===========test test value Test data from===========
MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /zht/index
       Parameters = {test=[Test data from]}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = cn.core.my.app.Controller.ZhtController
           Method = cn.core.my.app.Controller.ZhtController#index(Model, String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = /index
             View = null
        Attribute = name
            value = Welcome templates page

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Language:"en", Content-Type:"text/html;charset=UTF-8"]
     Content type = text/html;charset=UTF-8
             Body = <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>web page</title>
<link rel="stylesheet" href="../static/css/css.css" />
<style type="text/css">
</style>
</head>
<body>
Welcome to Welcome templates page
</body>
</html>
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

The results of Thymeleaf template production can be seen in the test, and we can use the test to debug the Thymeleaf template tag content when developing.

MVC structure of Spring boot project

When developing a WEB project, we must use the classic mvc pattern. The spring boot container corresponds to different mvc levels, and we create corresponding java classes at the object level. Let's make a sample together. This example is a typical Spring MVC Web application that uses MySQL operations.

MVC Map

  • Create service package cn. Core. My. App. Old service called bo layer
  • Create mapper package cn. Core. My. App. Old mapper called dao layer

1 Data Model Layer

Create a mybatis configuration sql file configuration file under the mapper file. Not familiar with mybatis, see my previous introductory articles about mybatis.

Database tables

CREATE TABLE `user` (
  `id` int(11) DEFAULT NULL,
  `user` varchar(255) COLLATE utf8_bin DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

UserSql.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.core.my.app.mapper.UserDao">
	<select id="addlist" resultType="map">
		select * from user
	</select>
</mapper>

UserDao class

package cn.core.my.app.mapper;
@Mapper
public interface UserDao {
	 List<Map> addlist(Map map);
}

UserService class

package cn.core.my.app.service;
@Service
public class UserService {
    @Autowired
    UserDao user;
    public List getOne(Map map){
        return user.addlist(map);
    }
}

See the following for database layer usage:
Springboot + MyBatis Getting Started Training 3 Multiple Data Sources and Caching and Data Connection Pool Settings
Springboot + MyBatis Getting Started Training 2 Change Delete and Query in like foreach Operation

2 Logical Layer and View Settings

Pass data layer data to logical layer spring container Controller, pass data to view model through container Controller, display data in html page through template Thymeleaf tag

ZhtController class

package cn.core.my.app.Controller;
@Controller
@RequestMapping("/zht")
public class ZhtController {
	@Autowired
	UserService user;
	@RequestMapping("/index")
	 public String index(Model map,String test) {
		System.out.println("===========Test Accessed===========");
		System.out.println("===========test test value "+test+"===========");
		map.addAttribute("name", "Welcome templates page");
		map.addAttribute("list", user.getOne(null));
	   return "/index";
	 }
}

index.html view

<html>
<head>
<meta http-equiv="Content-Type" 
      content="text/html; charset=utf-8" />
<title>web page</title>
<link rel="stylesheet" 
      href="../static/css/css.css" />
<style type="text/css">
</style>
</head>
<body th:inline="text">
Welcome[(${name})]
<table class="zht1" style="width:100%">
    <tr>
        <th width="15%">id</th>
        <th>Name</th>
    </tr>
    <th:block th:each="user:${list}">
    <tr>
        <td>[(${user.id})]</td>
        <td>[(${user.user})]</td>
    </tr>
    </th:block>
</table>
</body>
</html>

Browser http://localhost:9089/zht/index Input

The results show that

3 Testing and other configurations

application.yml configuration

server:
  port: 9089
spring:
  thymeleaf:
    cache: false
  mvc:
    static-path-pattern: /static/**
  http:
    encoding:
      force: true
      charset: utf-8
      enabled: true
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 10
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
    dynamic:
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/systext?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapperLocations: classpath*:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

  • servlet: context-path: /zht property sets the first level project access path

Database Table Settings

CREATE TABLE `user` (
  `id` int(11) DEFAULT NULL,
  `user` varchar(255) COLLATE utf8_bin DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

The test can run the test class MyUrlPageTest and see the test results in the background.

===========Test Accessed===========
===========test test value Test data from===========
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3dfe92ef] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [cn.core.my.app.mapper.UserDao]: 0.0
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@320ff86f] will not be managed by Spring
==>  Preparing: select * from user 
==> Parameters: 
<==    Columns: id, user
<==        Row: 1, username
<==        Row: 2, zht
<==      Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3dfe92ef]

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /zht/index
       Parameters = {test=[Test data from]}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {}
Handler:
             Type = cn.core.my.app.Controller.ZhtController
           Method = cn.core.my.app.Controller.ZhtController#index(Model, String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = /index
             View = null
        Attribute = name
            value = Welcome templates page
        Attribute = list
            value = [{id=1, user=username}, {id=2, user=zht}]

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Language:"en", Content-Type:"text/html;charset=UTF-8"]
     Content type = text/html;charset=UTF-8
             Body = <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>web page</title>
<link rel="stylesheet" href="../static/css/css.css" />
<style type="text/css">
</style>
</head>
<body>
Welcome to Welcome templates page
<table class="zht1" style="width:100%">
    <tr>
        <th width="15%">id</th>
        <th>Name</th>
    </tr>
    <tr>
        <td>1</td>
        <td>username</td>
    </tr>
    <tr>
        <td>2</td>
        <td>zht</td>
    </tr>
</table>
</body>
</html>
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

See the following for database layer usage:
Springboot + MyBatis Getting Started Training 3 Multiple Data Sources and Caching and Data Connection Pool Settings
Springboot + MyBatis Getting Started Training 2 Change Delete and Query in like foreach Operation

Topics: Java Spring Spring Boot Spring MVC IDEA