玩转spring boot,如何快速搭建一个MCV程序?这篇文章为大家详细主要介绍了一个MCV程序的快速搭建过程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
如何快速搭建一个MCV程序?
参照spring官方例子:https://spring.io/guides/gs/serving-web-content/
一、spring mvc结合thymeleaf模板
创建maven project后,修改pom.xml文件
4.0.0 com.github.carter659 spring02 0.0.1-SNAPSHOT jar org.springframework.boot spring-boot-starter-parent 1.4.2.RELEASE spring02 http://maven.apache.org UTF-8 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-maven-plugin
添加“MainController.java”这个控制器的类文件:
package com.github.carter659.spring02; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MainController { @GetMapping("/") public String index(Model model) { model.addAttribute("name", "刘冬"); return "index"; } }
修改App.java文件
package com.github.carter659.spring02; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
然后在项目中右键进入java build path
添加文件夹“And Folder”
在main目录下添加“resources”文件夹
修改"resources"的“Excluded”:
输入“**”
在src/main/resources下创建“templates”文件夹,并新建一个html文件“index.html”
MVC
输入http://localhost:8080 检测是否运行成功:
以上是使用thymeleaf模板做的动态页面,那么,如何在MVC应用中使用静态资源呢?
二、静态资源
在src\main\resources下新建“static”文件夹
并在其文件夹中复制进一张图片文件
修改之前的“index.html”文件,增加img标签
MVC
这时,立刻出现一个现象:
我们发现程序会自动热加载,这是因为在maven中依赖了“devtools”
最后,刷新网页,测试静态资源是否载入
PS:spring boot主推的是thymeleaf模板,而其语言用的是xml,个人认为不是非常方便。
代码下载:https://github.com/carter659/spring-boot-02.git
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持html中文网。
以上就是玩转spring boot MVC应用(2)的详细内容,更多请关注0133技术站其它相关文章!