spring-boot與web開發(fā)
- 創(chuàng)建應(yīng)用,選擇想要?jiǎng)?chuàng)建的場景
- 在配置文件中指定少量配置
- 編寫業(yè)務(wù)代碼
- xxxAutoConfigration給容器中配置主件
- xxxProperties封裝配置的內(nèi)容
靜態(tài)資源映射規(guī)則
WebMvcAutoConfiguration類
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(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
/webjars/**:所有這種類型的請(qǐng)求都去"classpath:/META-INF/resources/webjars/"這個(gè)路徑下找資源。(以jar包的方式引入靜態(tài)資源)
https://www.webjars.org/(一般以maven的方式引入前端框架)
http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js 利用webjars訪問公共資源
ResourceProperties配置類
//和靜態(tài)資源相關(guān)的配置
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;
}
staticPathPattern = "/**":如果訪問的路徑?jīng)]人處理,會(huì)默認(rèn)去CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};這些個(gè)資源下面找。
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
spring-boot初始化的時(shí)候只默認(rèn)建了static,我們就不麻煩建其它的文件夾了,默認(rèn)靜態(tài)文件就放在static。
歡迎頁映射(找所有靜態(tài)資源文件下的index.html頁面),由"/**"映射
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");
}
}
http://localhost:8080/ 就會(huì)找index.html頁面
FaviconConfiguration 圖標(biāo)配置
@Configuration
@ConditionalOnProperty(
value = {"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration implements ResourceLoaderAware {
private final ResourceProperties resourceProperties;
private ResourceLoader resourceLoader;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resolveFaviconLocations());
return requestHandler;
}
private List<Resource> resolveFaviconLocations() {
String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
List<Resource> locations = new ArrayList(staticLocations.length + 1);
Stream var10000 = Arrays.stream(staticLocations);
ResourceLoader var10001 = this.resourceLoader;
this.resourceLoader.getClass();
var10000.map(var10001::getResource).forEach(locations::add);
locations.add(new ClassPathResource("/"));
return Collections.unmodifiableList(locations);
}
}
頁面訪問的時(shí)候左上角的圖片"**/favicon.ico"也是在靜態(tài)資源文件夾下找
模版引擎 Thymeleaf(用于頁面與后端數(shù)據(jù)交互)
//把html頁面放在templates下面就可以自動(dòng)渲染了
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
Thymeleaf常用語法
//更改div的文本值,id,class等,即可以用th的任意屬性替換原生的屬性。
//其中傳入變量的方式大多數(shù)情況下使用"${...}"
<div th:text="${hello}" th:id="" th:class=""></div>
//"*{...}"基本和$一樣,在如下情況下,比"${...}"用著方便些
<div th:object="${session.user}">
//等同于${session.user.firstName}
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
//"#{...}"用于國際化
//"@{...}"用于定義url鏈接,傳入多個(gè)變量,用","分割即可
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
//對(duì)象遍歷,集合遍歷
List<User> users = new ArrayList<>();
map.put("users", users);
<table>
<tr th:each="user: ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>