window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

SpringBoot-05 Web开发

SpringBoot-05 Web开发

1

2

静态资源

要解决的第一个问题,静态资源存放问题,静态资源放在哪儿能查找到。

首先查看WebMvcAutoConfiguration.class(可以直接全局查找)

protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    
        //是否有自定义配置,有的话这个方法失效
    super.addResourceHandlers(registry);
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        
        //添加这个webjars,添加之后路径为:classpath:/META-INF/resources/webjars/
        ServletContext servletContext = this.getServletContext();
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            //其余可以识别的静态资源位置
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (servletContext != null) {
                registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});
            }

        });
    }
}

那么,什么是webjars

WebJars是一个很神奇的东西,可以让大家以jar包的形式来使用前端的各种框架、组件。WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。

3

我的理解就是:以 依赖的形式导入前端资源

结合上面的路径,我们导入一个jqury尝试:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>
4

可以看出 一一对应,也可以正常访问。

5

除了上面这些,还有其他可以识别静态资源的位置:

//其余可以识别的静态资源位置
registration.addResourceLocations(this.resourceProperties.getStaticLocations());//getStaticLocations()  点击
if (servletContext != null) {
    registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});
}

public String[] getStaticLocations() {
    return this.staticLocations;  //staticLocations  点击
}

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
 new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
              //  出现了路径

6

  • 在springboot,我们可以使用一下方式处理静态资源
    • webjars --------> localhost:8080/webjars/
    • public , static , /** , resources ------>localhost:8080/
  • 优先级 : resources > static > public,可以按照自己的需求,放入文件

至于 templates文件夹,其中的文件只能用 Controller 控制类,才可以进入。

首页设置

在SpringBoot中,默认自动识别在静态资源文件夹下的 index.html

注意:

  • 静态资源文件夹为:
    • public
    • static
    • resources
    • 优先级:resources > static > public
  • 默认的首页文件为:index.html,不要弄错。

下面测试放在了public,其余方法大家可以自行测试:

7

8

Thymeleaf模板引擎

1.导入依赖

模板引擎有什么用呢? 可以让你使用 Controller类 调用页面,没有Thymeleaf就是不可以。

首先!!,最重要的是导入这两个依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.4.3</version>
</dependency>

原因:自己创建的SpingBoor项目,自带的Thymeleaf版本为2.xxx,而我们要使用的这个版本为3.xx

大家导入依赖后确定是否成功:

9

10

之后更改一下pom.xml中的配置:

<properties>
    <java.version>1.8</java.version>
    <!-- 加入下面这两句 -->
    <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>3.0.4</thymeleaf-layout-dialect.version>
</properties>

2.Controller类测试

创建一个Controller类

注意:一定要在 xxxApplication启动器的同级目录下创建,不然不可能成功!!(踩了30分钟的坑)

13
@Controller
public class ThymeleafController {
    @RequestMapping("/a")
    public String test(){
        return "tt";
    }
}

创建一个html页面

注意:SpringBoot内部规定要在templates文件夹下创建xxx.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>ThymeleafController跳转</h1>
</body>
</html>

之后运行测试:

12

3.Thymeleaf语法

14

th:text

修改controller类,使用model传一个数据:

@RequestMapping("/a")
public String test(Model model){
    model.addAttribute("msg","Thymeleaf语法测试");
    return "tt";
}

修改html:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>ThymeleafController跳转</h1><br> 
    <!--以往都是直接${msg},在Thymeleaf中需要以下使用方法:-->
    <!--之前html可以用的标签,都变为:  th:属性名  -->
    <div th:text="${msg}"></div>
</body>
</html>
13

th:utext

修改controller类,使用model传一个数据:

@RequestMapping("/a")
public String test(Model model){
    model.addAttribute("msg","<h2>Thymeleaf语法测试</h2>");
    return "tt";
}

修改html:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>ThymeleafController跳转</h1><br>
    <div th:text="${msg}"></div><br>
    <div th:utext="${msg}"></div><br>
</body>
</html>
15

th:each

修改controller类,使用model传一个数据:

@RequestMapping("/a")
public String test(Model model){
    model.addAttribute("users", Arrays.asList("user1","user2","user3"));
    return "tt";
}

修改html:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>ThymeleafController跳转</h1><br>
<!--    两种写法,推荐第一种   -->
    <h3 th:each="user:${users}" th:text="${user}"></h3>
    <div th:each="user:${users}" >[[ ${user} ]]</div>
</body>
</html>

16

扩展SpringMVC

1.MVC扩展原理

diy视图解析器

@Configuration
public class MyMvcConfig {

    @Bean
    public ViewResolver MyViewResolver(){
        return new MyViewResolver();
    }


    public static class MyViewResolver implements ViewResolver{

        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

2.SpringMVC扩展

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        这句话的意思就是访问 ...8080/test, 跳转到tt.html页面
        registry.addViewController("/test").setViewName("tt");
    }
}

在SpringBoot中,有非常多的 xxxConfiguration 帮助我们进行扩展配置,只要看见了这个东西,我们就要注意了,可能是增加了一些新的功能。

个人博客为:
MoYu's HomePage
MoYu's Gitee Blog

posted @ 2021-03-31 22:26  MoYu-zc  阅读(296)  评论(0编辑  收藏  举报