spring-boot与web开发
- 创建应用,选择想要创建的场景
- 在配置文件中指定少量配置
- 编写业务代码
- xxxAutoConfigration给容器中配置主件
- xxxProperties封装配置的内容
静态资源映射规则
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/**:所有这种类型的请求都去"classpath:/META-INF/resources/webjars/"这个路径下找资源。(以jar包的方式引入静态资源)
https://www.webjars.org/(一般以maven的方式引入前端框架)
http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js 利用webjars访问公共资源
ResourceProperties配置类
//和静态资源相关的配置
@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 = "/**":如果访问的路径没人处理,会默认去CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};这些个资源下面找。
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
spring-boot初始化的时候只默认建了static,我们就不麻烦建其它的文件夹了,默认静态文件就放在static。
欢迎页映射(找所有静态资源文件下的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/ 就会找index.html页面
FaviconConfiguration 图标配置
@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);
}
}
页面访问的时候左上角的图片"**/favicon.ico"也是在静态资源文件夹下找
模版引擎 Thymeleaf(用于页面与后端数据交互)
//把html页面放在templates下面就可以自动渲染了
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的任意属性替换原生的属性。
//其中传入变量的方式大多数情况下使用"${...}"
<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链接,传入多个变量,用","分割即可
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
//对象遍历,集合遍历
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>