微服務 第二章:SpringBoot 創建web項目(用Thymeleaf模板引擎)


    springboot內部對jsp的支持並不是特別理想,而springboot推薦的視圖是Thymeleaf。Thymeleaf在其他隨筆中有所講述,這里不再重復。

    碼雲地址:https://gitee.com/yaohuiqin/SpringBootDemo

方法一:springboot的非web項目改成web項目

1、添加maven

  在第一章的代碼基礎上,添加maven

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

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

2、在resources文件夾下新建templates包,該包下放置靜態的html文件(模板引擎)

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
 <h1>您好:</h1>
 <h1 th:text="${name}"></h1>
</body>
</html>

 

3、新建一個Controller ,該Controller返回index.html 

@Controller
public class IndexController {
    @RequestMapping(value = "/index" ,method = RequestMethod.GET)
    public String returnIndex(ModelMap map){
        map.addAttribute("name", "yaohuiqin");
        return "index";
    }
}

 

4、運行項目,在瀏覽器上運行:

 方法2 :idea自動創建springboot的Web項目

 1、file > new >project

 

項目創建完成:項目結構如下 

 

 

如果用Thymeleaf模板引擎的html,需要添加對應的maven

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

 

最后新建controller和html頁面即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM