SpringBoot之Web开发基础

版权声明:原创文章, 欢迎转载. https://blog.csdn.net/ip_JL/article/details/84847086

回顾

SpringBoot之基础

SpringBoot之配置

SpringBoot之日志

开发步骤

① 创建SpringBoot应用, 选中所需的模块.

② 在配置文件中进行少量的配置

③ 编写业务逻辑代码

自动配置原理

xxxAutoConfiguration: 给容器自动配置组件

xxxProperties: 配置类封装配置文件的内容

SpringBoot对静态资源的映射规则

进入WebMvcAutoConfiguration:
//可以设置和静态资源有关的参数,缓存时间等
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//静态资源文件夹映射 if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); } } }

//配置欢迎页映射

@Configuration
@ConditionalOnProperty(
    value = {"spring.mvc.favicon.enabled"},
    matchIfMissing = true
)
public static class FaviconConfiguration {
    private final ResourceProperties resourceProperties;

    public FaviconConfiguration(ResourceProperties resourceProperties) {
        this.resourceProperties = resourceProperties;
    }

    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(-2147483647);
        //所有 **/favicon.ico
        mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
        return mapping;
    }

    @Bean
    public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
        return requestHandler;
    }
}

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

    webjars:以jar包的方式引入静态资源

    例如, 引入jquery的webjar包的依赖

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.3.1</version>
    </dependency>


    访问路径: localhost:8080/webjars/jquery/3.3.1/jquery.js

② "/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射

    "classpath:/META‐INF/resources/",
    "classpath:/resources/",
    "classpath:/static/",
    "classpath:/public/"
    "/":当前项目的根路径

    localhost:8080/[静态资源文件名] ==> 去静态资源文件夹里面找该文件

③ 首页(静态资源文件夹下的所有index.html页面), 被"/**"映射

    localhost:8080/  ==>  自动找index.html

④ 所有的 **/favicon.ico 都是在静态资源文件夹下找
    网站图标也在静态资源文件夹下找

模板引擎

模型图:

SpringBoot推荐的模板引擎: thymeleaf

① 引入thymeleaf

<!--引入thymeleaf模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--切换thymeleaf的版本-->
<properties>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <!--如果thymeleaf的版本为thymeleaf3 则适配thymeleaf-layout-dialect2以上-->
    <!--如果thymeleaf的版本为thymeleaf2 则适配thymeleaf-layout-dialect1以上-->
    <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

② thymeleaf的使用和语法

默认规则:

private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";  //默认前缀
public static final String DEFAULT_SUFFIX = ".html";  //默认后缀

所以, 只要把html页面放在classpath:/templates/, thymeleaf就能自动渲染了.

1) 导入thymeleaf的名称空间

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

2) 使用thymeleaf的语法

controller:

@RequestMapping("/success")
public String success(Map<String, Object> map){
    map.put("hello", "你好, thymeleaf!");
    //SpringBoot会在默认路径下找classpath:/templates/success.html
    return "success";
}

success.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试模板引擎thymeleaf3</title>
</head>
<body>
    <h3>成功访问...</h3>
    <!--th:text 将div里边的为本内容设置为指定的值-->
    <div th:text="${hello}"></div>
</body>
</html>

3) 语法规则

th:[任意html属性]  改变当前属性里面的内容

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

4) 表达式

Simple expressions(表达式语法)
    Variable Expressions: ${...}    OGNL表达式:

            1. 获取对象的属性, 调用方法

            2. 使用内置的基本对象: #ctx

                #ctx : the context object.
                #vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.
                #response : (only in Web Contexts) the HttpServletResponse object.
                #session : (only in Web Contexts) the HttpSession object.
                #servletContext : (only in Web Contexts) the ServletContext object.

                如: ${session.foo} ...

            3. 内置的工具对象

               #execInfo : information about the template being processed.
               #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
               #uris : methods for escaping parts of URLs/URIs
               #conversions : methods for executing the configured conversion service (if any).
               #dates : methods for java.util.Date objects: formatting, component extraction, etc.
               #calendars : analogous to #dates , but for java.util.Calendar objects.
               #numbers : methods for formatting numeric objects.
               #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
               #objects : methods for objects in general.
               #bools : methods for boolean evaluation.
               #arrays : methods for arrays.
               #lists : methods for lists.
               #sets : methods for sets.
               #maps : methods for maps.
               #aggregates : methods for creating aggregates on arrays or collections.
               #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
               如: ${#strings.toString(obj)} ...


    Selection Variable Expressions: *{...}    变量选择表达式: 在功能上和${}是一样的

        补充功能:

<div th:object="${session.user}">
    <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>

等同于

<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

        相当于将${session.user}的值赋给th:object, 然后*代表th:object


    Message Expressions: #{...}    获取国际化内容的
    Link URL Expressions: @{...}    定义url链接的

        <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>    //标准写法

        @{/order/process(execId=${execId},execType='FAST')}    //简写(并且可以传多个参数)


    Fragment Expressions: ~{...}    片段引用表达式

        <div th:insert="~{commons :: main}">...</div>

       <div th:with="frag=~{footer :: #main/text()}">
          <p th:insert="${frag}">
       </div>
Literals(字面量)
    Text literals: 'one text' , 'Another one!' ,…
    Number literals: 0 , 34 , 3.0 , 12.3 ,…
    Boolean literals: true , false
    Null literal: null
    Literal tokens: one , sometext , main ,…
Text operations(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators(条件运算, 如: 三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens(特殊操作)
    No-Operation: _

小测试:

@RequestMapping("/success")
public String success(Map<String, Object> map){
    map.put("hello", "<h3>你好啊!!!</h3>");
    map.put("users", Arrays.asList("zhangsan", "zhaoliu", "tianqi"));
    //SpringBoot会在默认路径下找classpath:/templates/success.html
    return "success";
}
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>

<hr/>

<h3 th:each="user:${users}" th:text="${user}"></h3>
<h5>
    <span th:each="user:${users}">[[${user}]]</span>
</h5>

关于SpringMVC的自动配置

SpringBoot对SpringMVC的默认配置:

● 自动配置了ViewResolver(视图解析器: 根据方法的返回值得到视图对象, 然后决定如何渲染(转发? 重定向? ...))

● 组合所有的视图解析器

● ViewResolver

    ○ 如何定制: 可以自己给容器中添加一个视图解析器, 自动将其组合进来

● 静态资源文件夹 / webjars

● 静态首页访问

● favicon.ico

● 自动注册Converter(转换器), Formatter(格式化器)

    ○ Converter: 类型转换使用(页面提交的数据都是文本, 需要转换器将其转换成各种类型的数据)

    ○ Formatter: 时间格式化使用(页面提交的时间数据也是文本, 需要格式化器将其格式化成具体的时间数据)    

   @Bean
   @ConditionalOnProperty(
       prefix = "spring.mvc",
       name = {"date-format"}    //需要在配置文件中配置日期格式化的规则
   )
   public Formatter<Date> dateFormatter() {
       return new DateFormatter(this.mvcProperties.getDateFormat());    //日期格式化组件
   }

    ○ 如何定制: 自己添加格式化器转换器, 只需要放入容器中即可

● HttpMessageConverters

    ○ SpringMVC用来转换http请求和响应的(对象  <==> JSON)

    ○ HttpMessageConverters需要从容器中确定, 获取所有的HttpMessageConverter

    ○ 如何定制: 自己将其放入容器中即可    

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter<?> additional = ...
        HttpMessageConverter<?> another = ...
        return new HttpMessageConverters(additional, another);    //返回一个HttpMessageConverters对象即可
    }
}

● MessageCodesResolver(定义错误代码生成规则)

●  ConfigurableWebBindingInitializer    

    protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {
        try {
            return (ConfigurableWebBindingInitializer)this.beanFactory.getBean(ConfigurableWebBindingInitializer.class);   //从容器中获取
        } catch (NoSuchBeanDefinitionException var2) {    //如果容器中拿不到
            return super.getConfigurableWebBindingInitializer();    //调用父类的方法
        }
    }
    protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {    //父类的方法
        ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
        initializer.setConversionService(this.mvcConversionService());
        initializer.setValidator(this.mvcValidator());
        initializer.setMessageCodesResolver(this.getMessageCodesResolver());
        return initializer;
    }

    ConfigurableWebBindingInitializer :

    public void initBinder(WebDataBinder binder, WebRequest request) {    //初始化WebDataBinder
        binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
        if (this.directFieldAccess) {
            binder.initDirectFieldAccess();
        }
   
        if (this.messageCodesResolver != null) {
            binder.setMessageCodesResolver(this.messageCodesResolver);
        }

        if (this.bindingErrorProcessor != null) {
            binder.setBindingErrorProcessor(this.bindingErrorProcessor);
       }

        if (this.validator != null && binder.getTarget() != null &&     this.validator.supports(binder.getTarget().getClass())) {
            binder.setValidator(this.validator);
        }

        if (this.conversionService != null) {
            binder.setConversionService(this.conversionService);
        } 

        if (this.propertyEditorRegistrars != null) {
            PropertyEditorRegistrar[] var3 = this.propertyEditorRegistrars;
            int var4 = var3.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                PropertyEditorRegistrar propertyEditorRegistrar = var3[var5];
                propertyEditorRegistrar.registerCustomEditors(binder);
            }
        }
    }

    ○ 初始化Web数据绑定器(WebDataBinder)

    ○ 返回的数据跟对象的绑定

    ○ 如何定制: 自己将组件添加进容器即可(其本身就是在容器中获取的)

扩展SpringMVC的配置:

配置文件:

<mvc:view‐controller path="/hello" view‐name="success"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
    </mvc:interceptor>
</mvc:interceptors>
编写一个配置类(@Configuration), 是WebMvcConfigurerAdapter类型, 但不能标注@EnableWebMvc.

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    // super.addViewControllers(registry);
    //浏览器发送 /testSuccess 请求来到 success
    registry.addViewController("/testSuccess").setViewName("success");
    }
}

原理:

① WebMvcAutoConfiguration是SpringMVC的自动配置类

② 在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)

③ 容器中所有的WebMvcConfigurer都会一起起作用

④ 自己定义的配置类也会起作用

全面接管SpringMVC:

只需要自己配置, 无需SpringBoot对SpringMVC的自动配置, 只需要在配置类上添加@EnableWebMvc即可

@EnableWebMvc

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    // super.addViewControllers(registry);
    //浏览器发送 /testSuccess 请求来到 success
    registry.addViewController("/testSuccess").setViewName("success");
    }
}

原理:

① @EnableWebMvc的核心
    @Import(DelegatingWebMvcConfiguration.class)
    public @interface EnableWebMvc {

② 

    @Configuration
    public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

③ 

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

④ @EnableWebMvc将WebMvcConfigurationSupport组件导入进来

⑤ 所以, SpringBoot对SpringMVC的自动配置失效

如何修改SpringBoot的默认配置

模式:

    ① SpringBoot在自动配置很多组件的时候,先看容器中有没有用户配置的(@Bean、@Component), 如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(如: ViewResolver), 则将用户配置的和自动配置的组合起来.

    ② 在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置.

猜你喜欢

转载自blog.csdn.net/ip_JL/article/details/84847086