SpringBoot的Web开发

SpringBoot的Web开发

1.使用SpringBoot

  1. 创建SpringBoot应用时,选用我们需要的模块

  2. SpringBoot默认将场景配置好(autoConfiguration),只需在配置文件中指定少量配置

  3. 编写业务代码

2.SpringBoot对静态资源的映射规则

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));
                }

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

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

  2. “/**"访问当前项目的任何资源

  3. 欢迎页以及HTML的静态资源文件,由“/**”映射

  4. 所有的**/ico在静态资源文件夹下去寻找

3.引入模板引擎

​ SpringBoot推荐使用的Thymeleaf模板引擎

#### 1.引入模板引擎

加maven依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
2.Thymeleaf的使用以及语法
private static final Charset DEFAULT_ENCODING;
    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";

可以看到,只需将HTML页面放置到template目录下,便可进行加载

1.导入thymeleaf的名称空间

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

2.使用语法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
成功
    <div th:text="${hello}"></div>
</body>
</html>

1.th:任意属性可替换HTML标签中的属性

2.表达式

Simple expressions:
    Variable Expressions: ${...}  获取变量值
    		1)获取对象属性,调用方法
    		2)使用内置的基本对象 
    Selection Variable Expressions: *{...} 
    		配合 th:object使用
    Message Expressions: #{...}    获取国际化内容
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...} 片段引用
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: _
    

使用thymeleaf的引用,通过该部分配置,如果项目的父目录发生改变,那么页面静态资源的加载不会发生异常,类似于下列语法

<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.3.0/dist/css/bootstrap.css}" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">

th: + 原生HTML属性 +“@{}”

4.SpringMvc的自动配置

1.自动配置

SpringBoot自动配置好了SpringMVC

默认配置好了:视图解析器(根据方法的返回值得到视图,视图对象决定页面动向)

​ 静态首页访问

​ 静态资源文件夹

​ 自动配置转换器,格式化器,

​ MessageConvert

​ …

2.扩展Springmvc

编写自定义配置类,同时继承WebMvcConfigurationSupport

@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/www").setViewName("success");
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer configurer = new WebMvcConfigurer(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index.html");
                registry.addViewController("/index.html").setViewName("index.html");
            }
        };
        return configurer;
    }
}

改配置相当于springmvc的拦截器与网页跳转

5.修改SpringBoot的配置

模式

​ 1)SpringBoot在配置组件时,先看容器中是否有用户自己配制的,如果有,优先使用用户的配置,没有,则自动配置

​ 2)会有xxxConfiguration帮我们进行配置

6.国际化

1) 编写国际化配置文件

2) 使用ResourceBundleMessageSource管理国际化资源文件

3) 在页面填写fmt:message取出国际化内容

步骤

1) 编写国际化配置文件,抽取页面需要显示的信息

在这里插入图片描述

2) SpringBoot自动配置好了管理国际化资源文件的组件

效果:根据浏览器中英文设置改变相应位置的信息

自定义点击国际化实现

先编写LocaleResolver

public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.getParameter("l");
        Locale local = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String [] split = l.split("_");
            local = new Locale(split[0],split[1]);
        }
        return local;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

再将之注入到容器中

@Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

效果图

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值