springboot与web开发

toov5      2022-05-03     157

关键词:

简介

 

使用SpringBoot;
1)、创建SpringBoot应用,选中我们需要的模块; 比如web等等
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码;

 

参考这里:

比如要连接数据库的:有数据库的配置

查看 @EnableConfigurationProperties中的 dataSourceProperties.class

@ConfigurationProperties(prefix = "spring.datasource")   //跟配置绑定
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {

 


自动配置原理?
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx

xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;

 

 

Web:

 

 关于web 就是 restful的栗子了

 

   restful web开发


 

Spring boot 最后打成个jar包,web开发时候,页面放哪里?

Spring boot对静态资源的映射规则

这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx

xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;

 

idea: ctrl+shift+n 

 

这个类里面有个方法: 添加资源映射

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/**")) {   //所有 /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/ 这里找资源

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

 参考:https://www.webjars.org/

 

<!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webjars下面资源的名称即可
<dependency>        
<groupId>org.webjars</groupId>            
<artifactId>jquery</artifactId>            
<version>3.3.1</version>            
</dependency> 

 引入后:

 

根据图生成地址

访问地址:http://localhost:8080/webjars/jquery/dist/jquery.js 

 

 在访问时候 只需要写webjars下面的资源名称即可

 

资源映射:


 

@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/"};

可以设置和静态资源有关的参数, 缓存时间等

 

 

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

classpath 等价于 Java包同级的目录

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

 

classpath:

 

比如:localhost:8080/abc === 去静态资源文件夹里面找abc

 

3)、欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
4)、所有的 **/favicon.ico 都是在静态资源文件下找;

 

其实都是可以配置的啊哈:

@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;

可以修改静态文件夹位置!

 

 

Spring boot 不支持jsp ,Spring boot推荐使用模板引擎。

Velocty FreeaKer 

 模板:

把数据和模板 交给模板引擎

 

Spring boot 推荐使用 Thymeleaf

引入thymeleaf ,开发

引入相应的starter

 

<dependency>        
<groupId>org.springframework.boot</groupId>            
<artifactId>spring‐boot‐starter‐thymeleaf</artifactId>            
           2.1.6  
</dependency>        
切换thymeleaf版本
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>        
<!‐‐ 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 ‐‐>        
<!‐‐ thymeleaf2   layout1‐‐>        
<thymeleaf‐layout‐dialect.version>2.2.2</thymeleaf‐layout‐dialect.version>        
  </properties>

 

Thymeleaf使用

 

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
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">

 

2、使用thymeleaf语法;

 

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF‐8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!‐‐th:text 将div里面的文本内容设置为 ‐‐>
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

 

 

 语法规则 自行学习吧 不详细介绍了

 

 

Spring Boot  与 Spring mvc 自动配置原理:


 

参考:https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications

  

1. Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC


以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration):
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans,自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))


到这个类里面去:

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
        TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

    public static final String DEFAULT_PREFIX = "";

    public static final String DEFAULT_SUFFIX = "";

    private static final String[] SERVLET_LOCATIONS = { "/" };

    @Bean
    @ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
    @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled",
            matchIfMissing = true)
    public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new OrderedHiddenHttpMethodFilter();
    }

    @Bean
    @ConditionalOnMissingBean(FormContentFilter.class)
    @ConditionalOnProperty(prefix = "spring.mvc.formcontent.filter", name = "enabled",
            matchIfMissing = true)
    public OrderedFormContentFilter formContentFilter() {
        return new OrderedFormContentFilter();
    }

这个类里面有这个配置:视图解析器  (我们可以给容器中添加视图解析器)

        @Bean
        @ConditionalOnBean(ViewResolver.class)
        @ConditionalOnMissingBean(name = "viewResolver",
                value = ContentNegotiatingViewResolver.class)
        public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
            resolver.setContentNegotiationManager(
                    beanFactory.getBean(ContentNegotiationManager.class));
            // ContentNegotiatingViewResolver uses all the other view resolvers to locate
            // a view so it should have a high precedence
            resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
            return resolver;
        }

小结:

ContentNegotiatingViewResolver:组合所有的视图解析器的;
如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;

(验证方法 在doDispatch方法 打断点 进来的是自己定义的视图解析器组件)

 

Support for serving static resources, including support for WebJars (see below).静态资源文件夹路
径,webjars
Static index.html support. 静态首页访问
Custom Favicon support (see below). favicon.ico
自动注册了 of Converter , GenericConverter , Formatter beans.
Converter:转换器; public String hello(User user):类型转换使用Converter
Formatter 格式化器; 2017.12.17===Date;

 

 

 

关于Spring mvc的扩展问题,大家可以了解下。

<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);
        //浏览器发送 /atguigu 请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

 

原理:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)

 

@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {    
      private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
 //从容器中获取所有的WebMvcConfigurer    
      @Autowired(required = false)
      public void setConfigurers(List<WebMvcConfigurer> configurers) {
          if (!CollectionUtils.isEmpty(configurers)) {
              this.configurers.addWebMvcConfigurers(configurers);
             //一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用;      
             @Override    
             // public void addViewControllers(ViewControllerRegistry registry) {
              //    for (WebMvcConfigurer delegate : this.delegates) {
               //       delegate.addViewControllers(registry);
               //   }
              }
          }
} 

 

 

3)、容器中所有的WebMvcConfigurer都会一起起作用;
4)、我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;

 

 

3、全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;

 

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

 

原理:
为什么@EnableWebMvc自动配置就失效了;

@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 {

 

4)@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;

5)、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

 

 

总结:

如何修改SpringBoot的默认配置

 

模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如
果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默
认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

 

springboot的web开发支持与thymeleat模板引擎(代码片段)

SpringBoot的Web开发支持与Thymeleat模板引擎Web开发是基于B/S架构的应用软件开发技术,分为前端(用户接口)和后端(业务逻辑和数据),前端的可视化及用户交互由浏览器实现,即以浏览器作为客户端,实现客户与服务... 查看详情

4.springboot的web开发1

一.回顾好的,同学们,那么接下来呢,我们开始学习SpringBoot与Web开发,从这一章往后,就属于我们实战部分的内容了;其实SpringBoot的东西用起来非常简单,因为SpringBoot最大的特点就是自动装配。使用SpringBoot的步骤:创建一个S... 查看详情

springboot与springmvc的区别

参考技术ASpringMVC和SpringBoot都是Spring家族的重要成员。Spring家族的使命就是为了简化而生。SpringMVC简化日常Web开发的,后来随着自身的发展,SpringMVC变得臃肿复杂,而SpringBoot则进一步简化了SpringMVC开发。SpringMVC为JavaWeb而生。Sprin... 查看详情

springboot的文件上传与下载(代码片段)

SpringBoot的文件上传与下载文件上传和下载是Web开发应用中最常用的功能之一,本次将学习在SpringBoot的web开发实例中实现文件的上传和下载。在实际web开发中,为了文件上传成功,必须将表单的method方法设置post,... 查看详情

springboot快速开发(简单web)

这是一个springboot基础配置文件介绍的demo。只涉及到控制层与前端的简单交互,用于验证代码的畅通。spring-boot pom.xml解释<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.o 查看详情

springboot最佳实践集成jsp与生产环境部署

...市面上仍有很多的公司在使用JSP,所以本文就来介绍一下SpringBoot怎么集成JSP开发,以及生产环境的详细部署方法。二、集成JSP开发环境SpringBoot2.0.4RELEASETomcat9.0.10IDEA(IntellijIDEA简称,下文统 查看详情

springboot:web开发-cors支持

一、简介Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等1.1、CORS与JSONP相比1、JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。2、使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更... 查看详情

springboot与springmvc的区别是啥?

...较繁琐于是为了简化开发者的使用,从而创造性地推出了Springboot,约定优于配置简化了spring的配置流程。3、说得更简便一些Spring最初利用“工厂模式”(DI)和“代理模式”(AOP)解耦应用组件大家觉得挺好用于是按照这种模... 查看详情

springboot2从入门到入坟|web场景开发篇:静态资源规则与定制化(代码片段)

写在前面从本篇文章开始,我们会来分析Web开发里面的一些简单功能。为了便于分析,这里我会使用SpringInitailizr神器来创建一个项目单独进行测试。使用SpringInitailizr神器来帮我们快速创建项目想必大家都会了,不过在这里我还... 查看详情

springboot2从入门到入坟|web场景开发篇:welcome与favicon功能(代码片段)

...是欢迎页,一个是自定义Favicon。欢迎页支持首先,来到SpringBoot官方文档中,并找到7.1.6.WelcomePage这一小节,这一小节的地址如下所示。https://docs.spring.io/spring-boot/docs/2.4.5/reference/html/spring-boot-features 查看详情

springboot2从入门到入坟|web场景开发篇:web开发简介

接下来,我们就要正式进入使用SpringBoot来进行Web开发的章节的学习中了,因为Web开发也是我们以后使用SpringBoot来进行应用开发的一个常见场景。Web开发简介由于Web开发里面所涉及到的小功能点、小细节点众多,再加上其牵扯到... 查看详情

springboot2从入门到入坟|web场景开发篇:web开发简介

接下来,我们就要正式进入使用SpringBoot来进行Web开发的章节的学习中了,因为Web开发也是我们以后使用SpringBoot来进行应用开发的一个常见场景。Web开发简介由于Web开发里面所涉及到的小功能点、小细节点众多,再加上其牵扯到... 查看详情

springboot的web部署,springboot开发非web程序

目录:1、SpringBoot的web项目部署为war2、SpringBoot的web项目部署为jar3、SpringBoot开发非Web程序   3.1、方式一:利用main()方法   3.2、方式二:通过springboot启动加载类CommandLineRunner#run()1、SpringBoot的web项目部署为war&... 查看详情

springboot的web开发

...Web开发的核心内容主要包括内嵌的Servlet容器和SpringMVC。SpringBoot使用起来非常简洁,大部分配置都有SpringBoot自动装配。SpringBoot的web支持SpringBoot提供了spring-boot-starter-web为web开发予以支持,而这个启动器内嵌了Tomcat以及Spri... 查看详情

重学springboot系列之整合静态资源与模板引擎(代码片段)

重学SpringBoot系列之整合静态资源与模板引擎webjars与静态资源springboot静态资源favicon.ico图标欢迎页面使用WebJars管理css&js1.pom中引入依赖2.访问引入的js文件自动检测依赖的版本测试模板引擎选型与未来趋势javaweb开发经历的几个... 查看详情

springboot2从入门到入坟|web场景开发篇:静态资源规则与定制化(代码片段)

写在前面从本篇文章开始,我们会来分析Web开发里面的一些简单功能。为了便于分析,这里我会使用SpringInitailizr神器来创建一个项目单独进行测试。使用SpringInitailizr神器来帮我们快速创建项目想必大家都会了,不过在这里我还... 查看详情

springboot(二):web综合开发

SpringBoot(二):web综合开发来源:纯洁的微笑,www.ityouknow.com/springboot/2016/02/03/springboot(二)-web综合开发.html如有好文章投稿,请点击→这里了解详情上篇文章介绍了Springboot初级教程:《 springboot(一):入门篇 》... 查看详情

springboot2从入门到入坟|web场景开发篇:welcome与favicon功能(代码片段)

...是欢迎页,一个是自定义Favicon。欢迎页支持首先,来到SpringBoot官方文档中,并找到7.1.6.WelcomePage这一小节,这一小节的地址如下所示。https://docs.spring.io/spring-boot/docs/2.4.5/reference/html/spring-boot-features.html#boot-features-spring-mvc-welcome-pa... 查看详情