SpringBoot-第7讲(与Web开发)

SpringBoot-第7讲(与Web开发)

文章目录


Web开发

一、使用SpringBoot

1)创建一个SpringBoot应用,选中我们需要的模块

2)SpringBoot默认将这些场景创建好,只需要在配置文件中指定少量配置就可以运行起来

3)自己编写业务代码,无需考虑乱七八糟的配置(前提搞清楚自动配置原理,这个场景SpringBoot帮我们配置了什么?能不能修改配置,怎么修改配置,能不能扩展该配置)

二、SpringBoot对静态资源的映射

1)所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源

webjars:以jar包的方式引入静态资源(各jar包引入版本参考:https://www.webjars.org/)

//在WebMvcAutoConfiguration.class中
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

示例:

2)静态资源可放置的目录

//@ConfigurationProperties(prefix="spring.resource",ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware{

}
//可以设置和资源有关的参数 主要是几个静态资源 比如缓存时间
//   "/**"访问当前项目的任何资源(静态资源的文件夹)
//   "classpath:/META-INF/resources/"
//   "classpath:/resources/"
//   "classpath:/static"
//   "classpath:/public"
//  "/":当前项目的根路径
      

示例:在对应目录下建文件夹即可,进而去对应目录下找静态资源。

3)欢迎页:静态资源文件下的所有的index.html页面,被" /** "映射

//欢迎页面的映射
 @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
            return welcomePageHandlerMapping;
        }


//WelcomePageHandlerMapping具体内容
 WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
        if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage.get());
            this.setRootViewName("forward:index.html");
        } else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
            logger.info("Adding welcome page template: index");
            this.setRootViewName("index");
        }

    }

4)配置图标也还是在**/favicon.ico 都是在静态文件下找

注意:

#在application.properties中配置
#配置自定义的静态文件夹 则将不访问SpringBoot要求的静态配置
spring.resources.static-locations=classpath:/hello/,classpath:/mln/

三、模板引擎

JSP Velocity Freemarker Thymeleaf 

SpringBoot推荐Thymeleaf - 语法简单 功能强大

1)引入Thymeleaf 

覆盖原来比较低的版本(注意两者要进行适配)

2)Thymeleaf 使用&语法

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
	//默认的模板资源路径
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	//默认解析html资源
	public static final String DEFAULT_SUFFIX = ".html";
	private boolean checkTemplate = true;
	private boolean checkTemplateLocation = true;
	private String prefix = DEFAULT_PREFIX;
	private String suffix = DEFAULT_SUFFIX;
	 //默认模式也是html的
	private String mode = "HTML";
	private Charset encoding = DEFAULT_ENCODING;
	 //默认开启缓存,项目没上线建议通过配置关闭,然后按F9就可以自动编译,避免影响调试
	private boolean cache = true;

	....
}
//只要我们吧HTML页面放到classpath:/template/,thymeleaf就能自动自动渲染

 语法可参考:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

使用:

1、导入thymeleaf的名称空间

<html xmlns:th="http://www.thymeleaf.org">

2、使用thymeleaf语法

<!DOCTYPE html>
<html>
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" data-th-href="@{/css/gtvg.css}" />
</head>
<body>
<p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>
<div id="" class="" th:id="${hello}"></diiv>
</body>
</html>

1)th:text:改变当前元素里面的文本内容

       th:任意html属性,来替换原生属性的值(讲解部分)

关键字功能介绍案例
th:utext文本替换,html标签会显示出正确的样式<p th:utext="#{home.welcome}"></p>即可。
   Welcome to our fantastic grocery store!
等效于html :<p>Welcome to our <b>fantastic</b> grocery store!</p>
th:style设置样式<div th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"></div>
th:onclick点击事件<td th:onclick = "'getCollect()'"></td>
th:each属性赋值<tr th:each = "user,userStat:${users}">
th:if判断条件<a th:if = "${userId}"> 如果userId不为空就执行a标签
th:unless和th:if判断相反<a th:href="@{/login} th:unless=${session.user != null}">Login</a>
th:href链接地址<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:selectdselected选择框选中th:selected="(${xxx.id} == ${configObj.dd})"
th:src图片类地址引入<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline定义js脚本可以使用变量<script type="text/javascript" th:inline="javascript">
th:action表单提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:remove删除某个属性<tr th:remove="all">
1.all:删除包含标签和所有的孩子。
2.body:不包含标记删除,但删除其所有的孩子。
3.tag:包含标记的删除,但不删除它的孩子。
4.all-but-first:删除所有包含标签的孩子,除了第一个。
5.none:什么也不做。这个值是有用的动态评估。
th:attr设置标签属性,多个属性可以用逗号分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值