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:selectd | selected选择框选中 | 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}",此标签不太优雅,一般用的比较少。 |