美文网首页
04.spring-boot与web开发

04.spring-boot与web开发

作者: 马晓钧 | 来源:发表于2019-01-20 15:54 被阅读0次

spring-boot与web开发

  1. 创建应用,选择想要创建的场景
  2. 在配置文件中指定少量配置
  3. 编写业务代码
- 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>

相关文章

  • 04.spring-boot与web开发

    spring-boot与web开发 创建应用,选择想要创建的场景 在配置文件中指定少量配置 编写业务代码 静态资源...

  • Android 网络应用最佳做法

    Best practices for web apps 与桌面 Web 开发相比,为移动设备开发网页和 Web 应...

  • 资深前端架构师推荐:小白必看的web前端基础书籍

    其实与web相关的书籍还是很多的,因为web的领域就是比较广的,因为有过web开发经验的都知道,web,就开发语言...

  • Go Web编程.epub

    【下载地址】 《Go Web编程》介绍如何用Go语言进行Web应用的开发,将Go语言的特性与Web开发实战组合到一...

  • Vagrant 虚拟环境利器

    开发环境之痛 软件开发少不了就是开发环境,Web开发对环境的依赖则更大。Web开发中,无论前端还是后端,都少不了与...

  • WebAPI设计之WebAPI

    什么是 Web API 在《Web API 的设计与开发》一书中,将 Web API 定义为使用 HTTP 协议通...

  • HTML基础

    新的征程 web前端介绍 web前端开发做什么 pc端web开发;移动端web开发;混合app开发;网页游戏/移动...

  • Web版扫雷开发小记(3)

    前篇: web版扫雷开发小记(1)web版扫雷开发小记(2)web版扫雷开发小记(3)web版扫雷开发小记(4) ...

  • Web与Web开发技术简介

    一、网络程序开发体系结构 C/S(Client/Server)即客户端/服务器结构。在这种结构中,服务器通常采用高...

  • 前言

    近年来,随着Web应用突飞猛进的发展,促使了Web应用开发语言的不断普及,越来越多的开发者开始学习与使用Web应用...

网友评论

      本文标题:04.spring-boot与web开发

      本文链接:https://www.haomeiwen.com/subject/ryixjqtx.html