SpringBoot学习(二)WEB开发

news2024/9/22 4:19:14

文章目录

  • WEB开发
    • `WebMvcAutoConfiguration`原理
      • 生效条件
      • 效果
      • `WebMvcConfigurer`接口
      • 静态资源源码规则
      • `EnableWebMvcConfiguration`规则
      • 容器中`WebMvcConfigurer`配置底层行为
    • Web场景
      • 自动配置
      • 默认效果
    • 静态资源
      • 默认规则
        • 静态资源映射
        • 静态资源缓存
        • 欢迎页
        • Favion
      • 自定义静态资源规则
        • 配置方式
        • 代码方式
    • 路径匹配
      • Ant风格路径用法
      • 模式切换
    • 内容协商
      • 多端内容适配
        • 默认规则
        • 配置协商规则与支持类型
      • 自定义内容返回
      • 内容协商原理-`HttpMessageConverter`
        • `@ResponseBody`由`HttpMessageConverter`处理
        • `WebMvcAutoConfiguration`提供集中默认`HttpMessageConverters`
    • 模板引擎
      • Thymeleaf整合
      • 基础语法
      • 控制
        • 遍历
        • 判断
        • 属性优先级
      • 变量选择
      • 模板布局
      • devtools
    • 错误处理
      • 默认机制
        • 流程
      • 示例
        • 前后端分离
        • 服务端页面渲染
    • 嵌入式容器
      • 自动配置原理
      • 自定义
      • 示例
    • 全接管SpringMVC
      • `WebMvcAutoConfiguration`自动配置的规则
      • `@EnableWebMvc`禁用默认行为
    • 实践
      • 三种方式
      • 两种模式

WEB开发

SpringBoot的WEB开发能力由SpringMVC提供

WebMvcAutoConfiguration原理

生效条件

@AutoConfiguration(after = { DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })//在这些自动配置后
@ConditionalOnWebApplication(type = Type.SERVLET)//若是web应用则生效,类型SERVLET
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)//容器中没有该Bean则生效,默认没有
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)//优先级
@ImportRuntimeHints(WebResourcesRuntimeHints.class)
public class WebMvcAutoConfiguration {...}

效果

  1. 类中存放了两个Filter:
  • HiddenHttpMethodFilter:页面表单提交Rest请求(GET、POST、PUT、DELETE)
  • FormContentFilter:表单内容Filter,GET(数据放URL后)、POST(数据放请求体)请求可以携带数据,PUT、DELETE请求体数据会被忽略
  1. 在容器中放置了WebMvcConfigurer组件,给SpringMVC添加各种定制功能
  • 所有功能最终和配置文件进行绑定
  • WebMvcPropertiesspring.mvc配置文件
  • WebPropertiesspring.web配置文件
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)//额外导入其他配置
@EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {

WebMvcConfigurer接口

提供了配置SpringMVC底层的所有组件入口
在这里插入图片描述

静态资源源码规则

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(),
			"classpath:/META-INF/resources/webjars/");
	addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
		registration.addResourceLocations(this.resourceProperties.getStaticLocations());
		if (this.servletContext != null) {
			ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
			registration.addResourceLocations(resource);
		}
	});
}
  1. 访问/webjars/**路径去classpath:/META-INF/resources/webjars/下寻找:

  2. 访问/**路径去静态资源默认位置寻找:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/
  1. 静态资源默认都有缓存规则的设置:浏览器访问了静态资源index.js,若其没有发生变化,下次访问则可以直接让浏览器用自己缓存中的内容
registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod()));
registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
registration.setUseLastModified(this.resourceProperties.getCache().isUseLastModified());
  • 所有缓存设置,直接通过spring.web配置文件设置/修改
  • cachePeriod:缓存周期,以秒为单位
  • cacheControl:HTTP缓存控制
  • useLastModified:是否使用最后一次修改,配合HTTP缓存规则

EnableWebMvcConfiguration规则

SpringBoot给容器中存入WebMvcConfigurationSupport组件,若开发者自己放置了这个组件,Boot中的WebMvcConfiguration都会失效

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(WebProperties.class)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {

*HandlerMapping:根据请求路径/a查找对应handler处理请求

  • WelcomPageHandlerMapping:找index.html,只要静态资源位置中存在该页面,则项目启动时默认访问

容器中WebMvcConfigurer配置底层行为

  1. WebMvcConfiguration是一个自动配置类,它存在一个EnableWebMvcConfiguration
  2. EnableWebMvcConfiguration继承于DelegatingWebMvcConfiguration,两类同时生效
  3. DelegatingWebMvcConfiguration利用 DI 将容器中所有WebMvcConfigurer注入
  4. 他人调用DelegatingWebMvcConfiguration的方法配置底层规则,其方法调用所有WebMvcConfigurer的配置底层方法

Web场景

自动配置

  1. 整合场景,引入starter-web
  2. 引入autoconfiguration
  3. @EnableAutoConfiguration注解使用@Import(AutoConfigurationImportSelector.class)批量导入组件
  4. 加载META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件配置所有组件
  5. 绑定配置文件的配置项:
  • SpringMVC的所有配置spring.mvc
  • Web场景通用配置spring.web
  • 文件上传配置spring.servlet.multipart
  • 服务器配置server,如编码方式等

默认效果

  1. 包含ContextNegotiatingViewResolverBeanNameViewResolver组件,方便视图解析
  2. 默认的静态资源处理机制,使静态资源在static文件夹下即可直接访问
  3. 自动注册ConverterGenericConverterFormatter组件,适配常见数据类型转换和格式化需求
  4. 支持HttpMessageConverters,便于返回JSON等数据类型
  5. 注册MessageCodesResolver,便于国际化及错误消息处理
  6. 支持静态index.html
  7. 自动使用ConfigurableWebBindingInitializer,实现消息处理、数据绑定、类型转化、数据校验等功能

静态资源

默认规则

静态资源映射
  1. 规则都定义在WebMvcAutoConfiguration
  2. /webjars/**—>classpath:/META-INF/resources/webjars/
  3. /**—>classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/
静态资源缓存

所有静态资源都定义了缓存规则,但此功能参数无默认值

  • Period:缓存周期,以秒为单位,默认0s
  • cacheControl:HTTP缓存控制,默认无
  • useLastModified:是否使用最后一次修改,配合HTTP缓存规则,默认false
欢迎页
  1. 静态资源目录下找index.html
  2. 没有时在templates下找index模板页
Favion

静态资源目录下找favicon.ico作为图标

自定义静态资源规则

配置方式
#spring.web
#开启静态资源映射规则
spring.web.resources.add-mappings=true
#设置缓存
spring.web.resources.cache.period=3600
#浏览器首次请求服务器,服务器告知最大留存时间7200s,此时间内此资源访问不需要再次请求
#覆盖 period 配置
spring.web.resources.cache.cachecontrol.max-age=7200
#使用资源上次修改时间,对比服务器和浏览器资源是否相同,相同返回304
spring.web.resources.cache.use-last-modified=true
#共享缓存
spring.web.resources.cache.cachecontrol.cache-public=true
#自定义静态资源文件夹位置
spring.web.resources.static-locations=classpath:/a/, classpath:/b/
#spring.mvc
#自定义webjars路径前缀
spring.mvc.webjars-path-pattern=/wj/**
#静态资源访问路径前缀
spring.mvc.static-path-pattern=/static/**
代码方式

只要容器中存在一个WebMvcConfigurer组件,配置的底层行为都会生效

//@EnableWebMvc
//标注则不再保留
@Configuration
//向容器中放置一个WebMvcConfigurer,就能自定义底层
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //保留
        WebMvcConfigurer.super.addResourceHandlers(registry);
        //自定义
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/a/")
                .setCacheControl(CacheControl.maxAge(1500, TimeUnit.SECONDS));
    }
}
@Configuration
public class MyConfiguration {
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/static/**")
                        .addResourceLocations("classpath:/a/")
                        .setCacheControl(CacheControl.maxAge(1500, TimeUnit.SECONDS));
            }
        };
    }
}

路径匹配

Spring5.3后,支持AntPathMatcher路径策略外,加入对PathpatternParser策略的支持

Ant风格路径用法

  1. 规则:
  • *:任意数量字符,*.html匹配任意扩展名为html的文件
  • ?:任意一个字符
  • **:任意数量的目录

/folder1/*/*.java匹配folder1目录下两级任意java文件;
/folder2/**.java匹配folder2目录下任意深度的java文件;

  • {}:一个命名的模式占位符,/{type}/{id}.html匹配任意{type}目录下任意{id}.html的文件
  • []:字符集合,[a-z]标识小写字母
  • 特殊字符转义如\\* \\?

模式切换

PathpatternParserAntPathMatcher提升了多倍吞吐量,降低部分空间分配率,兼容AntPathMatcher语法并支持更多类型路径模式,但**多段匹配只允许在模式末尾使用
默认路径匹配规则是PathpatternParser,切换语法:

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

内容协商

一套系统适配多端数据返回,SpringMVC拥有

多端内容适配

默认规则
  1. SpringBoot多端内容适配
  • 基于请求头:客户端向服务端发送请求,携带HTTP标准的Accept请求头(默认)

Accept:application/jsontext/xmltext/yml
服务器端根据客户端请求头期望的数据类型进行动态返回

  • 基于请求参数:(需要开启)

发送请求GET/projects/spring-boot?format=json
匹配到@GetMapping("/projects/spring-boot") 根据参数协商,优先返回 json 类型数据[需要开启参数匹配] 发送请求GET/projects/spring-boot?format=xml`优先返回 xml 数据类型

配置协商规则与支持类型

请求相同接口,可以返回 json 和 xml 不同格式数据。在web场景中已经默认引入了jackson包,直接享有json的操作。对xml的操作需要:

  1. 引入支持写出 xml 的依赖
<!--jackson-->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
  1. 标注
@JacksonXmlRootElement//写出xml文档
@Data
public class Person {
	private Long id; 
	private String userName;
}
  1. 开启基于请求参数的内容协商
##开启基于请求参数的内容协商功能,默认参数名:format
spring.mvc.contentnegotiation.favor-parameter=true
##指定内容协商时使用的参数名,默认参数名:format
spring.mvc.contentnegotiation.parameter-name=type 

自定义内容返回

  1. 增加yaml返回支持:
依赖
<!--yaml-->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
对象写出YAML
public static void main(String[] args) {
    Person person = new Person();
    person.setId(1L);
    person.setName("Max");
    YAMLFactory factory = new YAMLFctory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MAKER);
    ObjectMapper mapper = new ObjectMapper(factory);
    //...
}
配置,新增媒体类型
spring.mvc.contentnegotiation.media-types.yaml=text/yaml
  1. 增加其它类型
  • 配置媒体类型支持:spring.mvc.contentnegotiation.media-types.yaml=text/yaml
  • 编写对应的HttpMessageConverter,告知Boot这个支持的媒体类型
  • MessageConverter组件加入到底层:容器中存入WebMvcConfigurer组件,并配置底层MessageConverter
  1. HttpMessageConverter的示例写法
public class MyYAMLHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    //将对象转换为YAML
    private ObjectMapper objectMapper = null;
    public MyYAMLHttpMessageConverter() {
        //告知SpringBoot该Converter支持哪种媒体类型
        super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
        YAMLFactory factory = new YAMLFactory()
                .dissable(YAMLGenerator.Feature.WRITE_DOC_START_MAKER);
        this.objectMapper = new ObjectMapper(factory);
    }
    @Override
    protected boolean supports(Class clazz) {
        /*只要是对象类型,而非基本数据类型,就*/return false;
    }
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }
    @Override
    protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //try...with,自动关流
        try(OutputStream os = outputMessage.getBody()) {
            this.objectMapper.writeValue(os, methodReturnValue);
        }
    }
}

内容协商原理-HttpMessageConverter

定制HttpMessageConverter以实现多端内容协商:编写WebMvcConfigurer提供的configureMessageConverters底层,修改底层的MessageConverter

@ResponseBodyHttpMessageConverter处理

标注了@ResponseBody的返回值将会由支持它的HttpMessageConverter写给浏览器

  1. controller方法的返回值标注了@ResponseBody
  • 请求先来到DispatcherServletdoDispatch()方法处理
  • RequestMappingHandlerAdapter执行,调用invokeHandlerMethod()执行目标方法
  • 目标方法执行前,准备:

HandlerMethodArgumentResolver:参数解析器,确定目标方法每个参数值;
HandlerMethodReturnValueHandler:返回值处理器,确定如何处理目标方法的返回值

  • RequestMappingHandlerAdapter中的invokeAndHandle()真正执行目标方法
  • 目标方法执行完成,返回返回值对象
  • 找到合适的返回值处理器HandlerMethodReturnValueHandler
  • 最终使用RequestResponseBodyMethodProcessor处理标注了@ResponseBody的方法
  • RequestResponseBodyMethodProcessor调用writeWithMessageConverters,利用MessageConverter将返回值写回
  1. HttpMessageConverter进行内容协商
    在这里插入图片描述
  • 遍历所有的MessageConverter看谁支持此种内容类型数据
  • 需求json所以MappingJackson2HttpMessageConverter支持写出json
  • jackson使用ObjectMapper将对象写入
WebMvcAutoConfiguration提供集中默认HttpMessageConverters

EnableWebMvcConfiguration通过addDefaultHttpMessageConverters添加了默认的Messageconverter如下:

ByteArrayHttpMessageConverter:字节数据读写
StringHttpMessageConverter:字符串读写
ResourceHttpMessageConverter:资源读写
ResourceRegionHttpMessageConverter:分区资源读写
AllEncompassingFormHttpMessageConverter:表单xml/json读写
MappingJackson2HttpMessageConverter请求响应体Json读写

模板引擎

  • SpringBoot采取嵌入式Servlet容器,所以JSP默认不能使用。若需要服务端页面渲染,优先考虑使用模板引擎
    在这里插入图片描述
  • 模板引擎页面默认放在src/resources/templates
  • SpringBoot包含自动配置的模板引擎:
  • FreeMarker
  • Groovy
  • Thymeleaf
  • Mustache

Thymeleaf整合

<!--Thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 自动配置org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
  2. 属性绑定在ThymeleafProperties中,对应配置文件spring.thymeleaf
  3. 默认效果:
  • 所有模板页面在classpath:/templates/
  • 查找后缀名为.html的页面
  1. 示例
welcome.html
<!DOCTYPE h
<html lang=
<head>
    <meta c
    <title>
</head>
<body>
<h1>
    hello,<
</h1>
</body>
</html>
WelcomeController.java
@Controller//适配前后端不分离,服务器渲染
public class WelcomeController {
    @GetMapping("abc")
    public String hello(@RequestParam("name") String name,
                        Model model) {
        //模板的逻辑视图名
        //物理视图 = 前缀 + 逻辑视图名 + 后缀
        //真实地址 = classpath:/templates/welcome.html
        //将需要和页面共享的数据放入model
        model.addAttribute("msg", name);
        return "welcome";
    }
}

基础语法

  1. 引入thymeleaf名称空间获取提示
<html  lang="en" xmlns:th="http://www.thymeleaf.org">
  1. th:*:动态渲染指定的html标签属性值,或th指令(便利、判断等)
  • th:text:标签体内文本值渲染

th:utext:不将值中标签(若有的话)转义,按照目的显示

  • th:属性:标签指定属性渲染
  • th:attr:标签任意属性渲染
  • th:if th:each ...:其它th指令
eg.
<p th:text="${content}">内容</p>
<a th:href="${url}">login</a>
<img src="../../images/a.jpg" th:attr="src=@{/images/a.jpg},title=#{logo},alt=#{logo}" />
  1. 表达式:用来动态取值
  • ${}:变量取值;使用model共享给页面的值都用${}
  • @{}:url路径,配合${}可以很安全的传输地址
  • #{}:国际化消息
  • ~{}:片段引用
  • *{}:变量选择,配合th:object绑定对象
  1. 系统工具&内置对象
  • param:获取请求参数
  • session:直接访问javax.servlet.http.HttpSession与当前请求关联的对象
  • application:用于检索应用程序/servlet上下文属性
  • #execInfo:提供有关在 Thymeleaf 模板的相关信息
  • #messages:用于获取变量表达式内的外部化消息的实用方法
  • #uris:用于在处理url/uri编码解码
  • #conversions:允许在模板的任何点执行转换服务
  • #dates:处理日期工具类
  • #calendars:日历工具类
  • #temporals:JDK8+java.timeAPI工具类
  • #numbers:处理数字
  • #strings:字符串工具类
  • #objects:处理一般对象工具类
  • #bools:布尔类型处理
  • #arrays:处理数组
  • #lists:处理list工具类
  • #setsset集合工具类
  • #mapsmap工具类
  • #aggregates:聚合操作工具类
  • #ids:用于处理id可能重复的 方法

控制

遍历
  • 语法:th:each="param, state : ${集合}"
  • 若没有显式地设置状态变量,则Thymeleaf将创建⼀个默认变量,该变量名为迭代变量+“Stat”paramStat
<tr th:each="user,item:${users}">
	<td th:text="${item.index}"></td>
	<td th:text="${item.count}"></td>
	<td th:text="${item.size}"></td>
	<td th:text="${item.current}"></td>
	<td th:text="${item.even}"></td>
	<td th:text="${item.odd}"></td>
	<td th:text="${item.first}"></td>
	<td th:text="${item.last}"></td>
</tr>
<!--
index:当前迭代索引,从 0 开始。
count:当前迭代索引,从 1 开始。
size:迭代变量中的元素总数。
current:每次迭代的iter 变量。
even/odd:当前迭代是偶数还是奇数。
first:当前迭代是否是第一个。
last:当前迭代是否是最后一次。
-->
判断
  1. th:if
eg.
<td th:if="${#strings.isEmpty(person.email)}" th:text="cant connect"></td>
<td th:if="${not #strings.isEmpty(person.email)}" th:text="${person.email}"></td>
  1. th:switch
<td th:switch="${animal.kind}">
    <p th:case="cats" th:color="red">cat</p>
    <p th:case="dogs" th:color="blue">dog</p>
</td>
属性优先级

当标签中有多个属性时,按照优先级执行

OrderFeatureAttributes
1片段包含th:insert th:replace
2遍历th:each
3判断th:if th:unless th:switch th:case
4定义本地变量th:object th:with
5通用方式属性修改th:attr th:attrprepend th:attrappend
6指定属性修改th:value th:href th:src ...
7文本值th:text th:utext
8片段指定th:fragment
9片段移除th:remove

变量选择

<div>
    <p>name:<span th:text="${animal.kind.name}">cookie</span></p>
</div>
<!--替换-->
<div th:object="${animal.kind}">
    <p>name:<span th:text="*{name}">cookie</span></p>
</div>

模板布局

  1. 定义模板:th:fragment
  2. 引用模板:~{templatename :: selector}
  3. 插入模板:th:insert th:replace
fragment.html
<footer th:fragment="myFooter" ...></footer>
quote.html
<div th:replace="~{fragment :: myFooter}"></div>

devtools

html中的修改使用ctrl+F9即可刷新页面效果;
Java代码中的修改不建议使用此工具,易引起某些不易排查的问题

<!--devtools热启动工具-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

错误处理

默认机制

  1. 默认机制储存在ErrorMvcAutoConfiguration
  • SpringBoot会自适应处理错误,区分响应页面或JSON数据
  • SpringMVC的错误处理机制仍旧发挥作用,处理不了时再移交给Boot处理
  1. 错误发生后,会被转发给/error路径,SpringBoot在底层放置了一个BasicErrorController组件,专门处理该请求
//返回HTML
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
	HttpStatus status = getStatus(request);
	Map<String, Object> model = Collections
		.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
	response.setStatus(status.value());
	ModelAndView modelAndView = resolveErrorView(request, response, status, model);
	return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
//返回 ResponseEntity,JSON
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
	HttpStatus status = getStatus(request);
	if (status == HttpStatus.NO_CONTENT) {
		return new ResponseEntity<>(status);
	}
	Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
	return new ResponseEntity<>(body, status);
}
  1. 错误页面解析
//解析错误视图地址
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
//若解析不到,则给出 error 默认错误页
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
  1. 容器中有一个默认名为error的视图,提供了默认白页
@Bean(name="error")
@ConditionlOnMissBean(name="error")
public View defaultErrorView() {
	return this.defaultErrorView;
}
流程
  1. 在错误移交至Boot手中后,受BasicErrorController管理
  2. 需求JSON数据,则DefaultErrorAttributes获取信息并返回
  3. 需求页面
  • templates/error中精确匹配错误状态码对应的页面
  • 在静态资源目录中匹配4xx.html5xx.html对应页面
  • 匹配error视图
  • SpringBoot默认提供的名为error的页面

示例

前后端分离

后台发生的所有错误,统一由@ControllerAdvice + @ExceptionHandler进行异常处理

服务端页面渲染
  1. classpath/templates/error下,放置精确匹配精确码.html
  2. classpath/templates/error下,放置模糊匹配4(5)xx.html
  3. 业务错误:
  • 核心业务:每种错误都应有代码控制,跳转至对应定制的错误页面
  • 通用业务:classpath/templates/error.html页面显示错误信息

嵌入式容器

管理、运行Servlet组件的环境,一般指服务器

自动配置原理

  • SpringBoot默认嵌入Tomcat作为Servlet容器
  • 自动配置类为ServletWebServerFactoryAutoConfigurationEmbeddedWebServerFactoryCustomizerAutoConfiguration
  • 自动配置类开始分析功能:*AutoConfiguration
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass(ServletRequest.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(ServerProperties.class)
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
		ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
		ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
		ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration {...}
  1. ServletWebServerFactoryAutoConfiguration自动配置了嵌入式容器场景
  2. 绑定ServerProperties配置类,所有服务器相关的配置server
  3. ServletWebServerFactoryAutoConfiguration导入了Tomcat、Jetty、Undertow
  • 导入嵌入式服务器都有条件注解,系统中须有此类(已导包)
  • 默认Tomcat配置,向容器中放置TomcatServletWebServerFactory
  • ServletWebServerFactory放置web服务器工厂
  • web服务器工厂使用getWebServer获取web服务器
  • TomcatServletWebServerFactory创建tomcat
  1. IoC容器ServletWebServerApplicationContext,启动时调用创建web服务器
  2. Spring容器刷新(启动)时存在一个时机用以刷新子容器
  3. refresh()容器刷新会调用onRefresh()

自定义

切换已提供的服务器:

<properties>
    <servlet-api.version>3.1.0</servlet-api.version>
</properties>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
       <!--ban tomcat-->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--use jetty-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

示例

用法:

  • 修改server下的相关配置可以修改服务器参数
  • 通过给容器中放一个ServletWebServerFactory以禁用SpringBoot默认的服务器工厂,实现自定义嵌入

全接管SpringMVC

  • SpringBoot默认配置了SpringMVC所有常用特性
  • 若我们需要全面接管SpringMVC并禁用所有默认配置,只需WebMvcConfigurer配置类并标注@EnableWebMvc即可

WebMvcAutoConfiguration自动配置的规则

在这里插入图片描述
在这里插入图片描述

@EnableWebMvc禁用默认行为

  1. @EnableWebMvc向容器中导入DelegatingWebMvcConfiguration组件,其自身继承WebMvcConfigurationSupport
  2. WebMvcConfiguration存在核心注解@ConditionalOnMissingBean(WebMvcConfigurationSupport.class):容器中没有WebMvcConfigurationSupportWebMvcConfiguration才生效

实践

  • SpringBoot已经默认配置了Web开发常用功能

三种方式

全自动直接标注控制器逻辑全部使用自动配置默认效果
半自动@Configuration+WebMvcConfigurer+WebMvcRegistrations
不标注@EnableWebMvc
自动配置效果
手动设置部分功能
定义MVC底层组件
全手动@Configuration+WebMvcConfigurer
标注@EnableWebMvc
禁用自动配置效果
全手动设置

两种模式

  1. 前后端分离模式:@RestController响应JSON数据
  2. 前后端不分离模式:@Controller+Thymeleaf模板引擎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1596532.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

PINet车道线检测+YOLOv8视频目标检测

前言&#xff1a; 本文主要目的是实现在PINet车道线检测的代码中嵌入YOLOv8的目标检测模块&#xff0c;具体效果如图所示&#xff1a; 在学习和使用YOLOv8进行目标检测时&#xff0c;感觉可以和最近研究的车道线检测项目结合起来&#xff0c;形成一套如上图所示的视频效…

2024/4/14周报

文章目录 摘要Abstract文献阅读题目创新点CROSSFORMER架构跨尺度嵌入层&#xff08;CEL&#xff09;CROSSFORMER BLOCK长短距离注意&#xff08;LSDA&#xff09;动态位置偏置&#xff08;DPB&#xff09; 实验 深度学习CrossFormer背景维度分段嵌入&#xff08;DSW&#xff09…

【图像分类】基于深度学习的轴承和齿轮识别(ResNet网络)

写在前面: 首先感谢兄弟们的关注和订阅,让我有创作的动力,在创作过程我会尽最大能力,保证作品的质量,如果有问题,可以私信我,让我们携手共进,共创辉煌。(专栏订阅用户订阅专栏后免费提供数据集和源码一份,超级VIP用户不在服务范围之内,不想订阅专栏的兄弟们可以私信…

如何远程连接电脑?

远程连接电脑是一种技术&#xff0c;能够使用户在不同地点的电脑之间建立连接&#xff0c;实现互相访问和控制的功能。这项技术为我们提供了便利和效率&#xff0c;使得随时随地的协同办公、异地统一管理和远程数据采集管理成为可能。 【天联】的使用场景 远程连接电脑的应用非…

SAP 转储单库存可用性检查详解

客户需求在下转储单以及公司间STO时候检查发货方是否库存够,如果有库存则可以创建,没有则不让创建。以免在DN过账时候才提示库存不够,把检查库存是否充足前移。 我们知道销售单是有可用性检查功能的,那么采购转储单是否也有同样功能呢? 可用性检查控制可理解为检查组和检…

微信小程序认证指南及注意事项

如何认证小程序&#xff1f; 一、操作步骤 登录小程序后台&#xff1a; https://mp.weixin.qq.com/ (点击前往) 找到设置&#xff0c;基本设置&#xff1b; 在【基本信息】处有备案和认证入口&#xff1b; 点击微信认证的【去认证】; 按照步骤指引一步步填写信息&#xff…

使用阿里云试用Elasticsearch学习:Search Labs Tutorials 搭建一个flask搜索应用

文档&#xff1a;https://www.elastic.co/search-labs/tutorials/search-tutorial https://github.com/elastic/elasticsearch-labs/tree/main/example-apps/search-tutorial Full-Text Search

盲人出行安全保障:科技革新助力无障碍生活新纪元

作为一名资深记者&#xff0c;我有幸见证了一场科技如何深刻改变视障群体生活的壮丽篇章。在这场变革中&#xff0c;盲人出行安全保障成为焦点&#xff0c;一款融合先进科技与人文关怀的辅助应用正以前所未有的力量&#xff0c;帮助盲人朋友们打破传统束缚&#xff0c;实现安全…

每日OJ题_BFS解决最短路④_力扣675. 为高尔夫比赛砍树

目录 力扣675. 为高尔夫比赛砍树 解析代码 力扣675. 为高尔夫比赛砍树 675. 为高尔夫比赛砍树 难度 困难 你被请来给一个要举办高尔夫比赛的树林砍树。树林由一个 m x n 的矩阵表示&#xff0c; 在这个矩阵中&#xff1a; 0 表示障碍&#xff0c;无法触碰1 表示地面&…

【大语言模型】基础:余弦相似度(Cosine similarity)

余弦相似度是一种用来确定两个向量之间相似性的度量。它在数据科学、信息检索和自然语言处理&#xff08;NLP&#xff09;等多个领域被广泛使用&#xff0c;用于度量在多维空间中两个向量之间角度的余弦。这个指标捕捉的是方向上的相似性而非大小&#xff0c;使其非常适合比较长…

专业SEO优化指南:设置网站关键词的详细步骤

在网站SEO优化的过程中&#xff0c;关键词的设置是提升网站排名的关键步骤之一。那么&#xff0c;作为一名专业的SEO人员&#xff0c;如何有效地进行关键词设置呢&#xff1f;以下是一些详细的步骤&#xff1a; 1. 确定网站的核心关键词。 这需要深入理解网站的主题或产品。通…

结合创新!ResNet+Transformer,高性能低参数,准确率达99.12%

今天给各位介绍一个发表高质量论文的好方向&#xff1a;ResNet结合Transformer。 ResNet因其深层结构和残差连接&#xff0c;能够有效地从图像中提取出丰富的局部特征。同时&#xff0c;Transformer的自注意力机制能够捕捉图像中的长距离依赖关系&#xff0c;为模型提供全局上…

GPT人工智能在线网页版大全

平民不参与内测&#xff0c;还能使用 ChatGPT 吗&#xff1f; 自去年 ChatGPT 爆红以来&#xff0c;关于它的消息铺天盖地。如果你真的想使用它&#xff0c;途径有很多。除了官方网站外国内还有许多 ChatGPT 的镜像网站&#xff0c;其中不乏免费的 3.5 版本。虽然有些网站需要…

byobu

byobu 终端多路复用器 一、byobu 安装二、byobu 使用三、其他终端多路复用器四、ssh byobu 远程协作 系统环境: linux(ubuntu,debian,kali) 一、byobu 安装 byobu 是包装过的tmux #sudo apt install tmux sudo apt install byobubyobu二、byobu 使用 创建窗口: Ctrl a c…

秋招复习笔记——八股文部分:网络基础

TCP/IP 网络模型 应用层 最上层的&#xff0c;也是我们能直接接触到的就是应用层&#xff08;Application Layer&#xff09;&#xff0c;我们电脑或手机使用的应用软件都是在应用层实现。那么&#xff0c;当两个不同设备的应用需要通信的时候&#xff0c;应用就把应用数据传…

使用 Tranformer 进行概率时间序列预测实战

使用 Transformers 进行概率时间序列预测实战 通常&#xff0c;经典方法针对数据集中的每个时间序列单独拟合。然而&#xff0c;当处理大量时间序列时&#xff0c;在所有可用时间序列上训练一个“全局”模型是有益的&#xff0c;这使模型能够从许多不同的来源学习潜在的表示。…

写一个uniapp的登录注册页面

一、效果图 二、代码 1、登录 &#xff08;1&#xff09;页面布局代码 <template><view class"normal-login-container"><view class"logo-content align-center justify-center flex"><image class"img-a" src"/s…

Maven超详细使用

定义 是一款用于管理和构建java项目的工具 作用 1. 依赖管理 2. 统一项目结构 3. 项目构建 项目目录结构 POM 项目对象模型 (Project Object Model) POM (Project Object Model) &#xff1a;指的是项目对象模型&#xff0c;用来描述当前的maven项目。 仓库 本地仓库&#…

【深度学习|基础算法】3.VggNet(附训练|推理代码)

这里写目录标题 1.摘要2.Vgg的网络架构3.代码backbonetrainpredict 4.训练记录5.推理onnxruntime推理export_onnx openvino推理tensorrt推理 1.摘要 vgg是由牛津大学视觉几何组&#xff08;Visual Geometry Group&#xff09;的这篇论文中提出的模型&#xff0c;并且在2014年的…

C#版Facefusion ,换脸器和增强器

C#版Facefusion &#xff0c;换脸器和增强器 目录 说明 效果 项目 调用代码 说明 Facefusion是一款最新的开源AI视频/图片换脸项目。是原来ROOP的项目的延续。项目官方介绍只有一句话&#xff0c;下一代换脸器和增强器。 代码实现参考 https://github.com/facefusion/f…