Spring Boot Practice Toss (8): Web Development - Simplify MVC

Mark Twain said, it's not the world that gets you into trouble; it's the world that ultimately doesn't make you think.

Simplify MVC

Spring MVC is very common now, but the cumbersome configuration still makes us sometimes want to abandon it. Microservices are becoming more and more popular now, but not all teams are suitable for microservices. As for why, let’s think about it first.

The traditional MVC model has helped us solve too many problems. However, some scenarios may not be very suitable, such as responsive trigger scenarios under the mobile Internet.

Just like in the past, we always said that process-oriented programming is not as good as object-oriented programming, but functional programming proposed in java 8 is also a kind of process-oriented programming, but it is more efficient for data processing. process oriented.

And Spring Boot has greatly optimized the MVC operation process to a certain extent (at least without the tedious configuration of a lot of XML files). Let's start with a simple example to simplify our web MVC programming.

Thymeleaf template engine

Spring Boot comes with many template engines, including FreeMarker, Groovy, Thymeleaf, Velocity, and Mustache. Thymeleaf is officially recommended as a template engine in Spring Boot. We can also choose according to usage habits and needs, and the principles are similar.

Thymeleaf is a Java class library, which is an xml/xhtml/html5 template engine, mainly used as the View layer of MVC Web applications.

Thymeleaf also provides additional modules to integrate with Spring MVC, so we can use Thymeleaf to completely replace JSP.

traditional practice

The traditional way of integrating the view layer with Spring MVC generally has four steps -

1. Create a web project
2. Add Thymeleaf dependencies
3. Write an index.html using Thymeleaf syntax (for example, accessing model data, iterating over data, judging data, etc.)
4. Configuring integration in Spring MVC

The specific details will not be introduced in detail here. The usage of Spring Boot will be introduced below. Let’s first look at the final renderings:
write picture description here

Thymeleaf Support for Spring Boot

Spring Boot automatically configures Thymeleaf through the org.springframework.boot.autoconfigure.thymeleaf package, as shown in the figure:

ThymeleafAutoConfigurationBeans required for integration are automatically configured through classes, including the configuration of templateResolver, templateEngineand thymeleafViewResolver.

By ThymeleafProperties来configuring Thymeleaf, in application.properties, start with spring.thymeleaf. By looking at the main source code of ThymeleafProperties, we can see how to set properties and default configuration:

spring.thymeleaf.xxxx=xxxxx

Here's a look at the class definition of ThymeleafProperties, which contains the properties we can set

actual combat

1. Create a new Spring Boot project

You can refer to boot-start to build. If you use my demo code, you can add a maven project directly under the main project.

2. Add Thymeleaf dependencies

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

Select Thymeleaf dependency, spring-boot-starter-thymeleaf will automatically include spring-boot-starter-web, as shown in Figure 7-3.

3. Example Bean

public class Man {

    private String name;
    private Integer phone;

    public Man() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPhone() {
        return phone;
    }

    public void setPhone(Integer phone) {
        this.phone = phone;
    }
}

This class is used to display data on the template page, including the name attribute and phone attribute:

4. Add static files

According to the default principle, static files such as script styles and images should be placed under src/main/resources/static, where Bootstrap and jQuery are introduced.

5. Template file

Pages are placed under src/main/resources/templates. Create a new index.html under src/main/resources/templates, as shown in the figure, the
write picture description here
index.html code is as follows:

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/>
    <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/>
</head>
<body>

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">访问model</h3>
    </div>
    <div class="panel-body">
        <span th:text="${singleMan.name}"></span>
    </div>
</div>

<div th:if="${not #lists.isEmpty(mans)}">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">列表</h3>
        </div>
        <div class="panel-body">
            <ul class="list-group">
                <li class="list-group-item" th:each="man:${mans}">
                    <span th:text="${man.name}"></span>
                    <span th:text="${man.phone}"></span>
                    <button class="btn" th:onclick="'getName(\'' + ${man.name} + '\');'">获得名字</button>
                </li>
            </ul>
        </div>
    </div>
</div>

<script th:src="@{jquery-3.3.1.min.js}" type="text/javascript"></script><!-- 2 -->
<script th:src="@{bootstrap/js/bootstrap.min.js}"></script><!-- 2 -->

<script th:inline="javascript">
    var single = [[${singleMan}]];
    console.log(single.name+"/"+single.phone)

    function getName(name){
        console.log(name);
    }
</script>

</body>
</html>

6. Data Services

The BaseController code is as follows:

@Controller
@SpringBootApplication
public class BaseController {
    public static void main(String[] args) {
        SpringApplication.run(BaseController.class,args);
    }

    @RequestMapping(value = {"/","/index.html"})
    public String returnView(Model model){

        Man single = new Man("aa",11);

        List<Man> mans = new ArrayList<>();

        Man p1 = new Man("bb",11);
        Man p2 = new Man("cc",22);
        Man p3 = new Man("zz",33);
        mans.add(p1);
        mans.add(p2);
        mans.add(p3);

        model.addAttribute("singleMan", single);
        model.addAttribute("mans", mans);

        return "index";
    }
}

7. Run

Visit http://localhost :8080, the effect is as shown before.

summary

This article uses Spring Boot to simplify a lot of configuration in MVC development, and mainly introduces how to use the template engine in Spring Boot.

Sample code address: boot-web

Reference resources

1. Spring Boot
2. Thymeleaf official website: http://www.thymeleaf.org
3. BootStrap Chinese website: http://www.bootcss.com/
4. jQuery API Chinese document: https://www.jquery123.com /

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325173569&siteId=291194637