Table of Contents
2.1:所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
2.2:"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
4.1:Spring MVC auto-configuration
8.2:注册Servlet三大组件【Servlet、Filter、Listener】
四:WEB开发
1:web开发简介
使用SpringBoot;
1)、创建SpringBoot应用,选中我们需要的模块;
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码;
自动配置原理?
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx
xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;
2:SpringBoot对静态资源的映射;
2.1:所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
webjars:以jar包的方式引入静态资源;
在pom文件中引入:
就可以访问静态资源:http://127.0.0.1:8088/webjars/jquery/3.5.1/jquery.js
2.2:"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
加载自己的静态资源
要找下面的/**资源
到下面找:
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
将文件放入上述文件夹后可以访问:http://127.0.0.1:8088/asserts/js/Chart.min.js
2.3:欢迎页的处理
静态资源文件夹下的所有index.html页面;被"/**"映射
2.4:配置浏览器喜欢的图标
所有的 **/favicon.ico 都是在静态资源文件下找;
//配置喜欢的图标
@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(Ordered.HIGHEST_PRECEDENCE + 1);
//所有 **/favicon.ico
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler
.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
ps:图标访问不到记得清缓存!!!
3:模板引擎
模板引擎种类:JSP、Velocity、Freemarker、Thymeleaf
SpringBoot推荐的Thymeleaf;
语法更简单,功能更强大;
3.1:引入thymeleaf
<!-- 引入thymeleaf启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2:thymeleaf语法
只要我们把HTML页面放在classpath:/templates/,以.html结尾,thymeleaf就能自动渲染;
第一步:导入thymeleaf的名称空间,为了能自动提示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
第二部:使用thymeleaf语法
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<div th:text="${hello}"></div>
</body>
</html>
3.3:语法规则;
1:th:text;改变当前元素里面的文本内容;
th:任意html属性;来替换原生属性的值
2:表达式
Simple expressions:(表达式语法)
一: Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#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 would be obtained using #{…} syntax.
#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).
二: Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:
<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>
三:Message Expressions: #{...}:获取国际化内容
四:Link URL Expressions: @{...}:定义URL;
@{/order/process(execId=${execId},execType='FAST')}
五:Fragment Expressions: ~{...}:片段引用表达式
<div th:insert="~{commons :: main}">...</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: _
简单例子:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>
<!--th:each在那个标签上,每次遍历都会生成这个标签,这是3个h4-->
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>
<h4>
<!--写一个行内写法-->
<span th:text="${user}" th:each="user:${users}"></span>
</h4>
</body>
</html>
4:SpringMvc的自动配置
4.1:Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)
1:Inclusion of ContentNegotiatingViewResolver
and BeanNameViewResolver
beans.
-
自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))
-
ContentNegotiatingViewResolver:组合所有的视图解析器的;
-
如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来
2:Support for serving static resources, including support for WebJars (see below).静态资源文件夹路径,webjars
3:Static index.html
support. 静态首页访问
4:Custom Favicon
support (see below). favicon.ico
5:自动注册了 of Converter
, GenericConverter
, Formatter
beans.
-
Converter:转换器; public String hello(User user):接口接受数据类型转换使用Converter
-
Formatter
格式化器; 2017.12.17===Date; - 自己添加的格式化器转换器,我们只需要放在容器中即可
6:Support for HttpMessageConverters
(see below).
-
HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User---Json;
-
HttpMessageConverters
是从容器中确定;获取所有的HttpMessageConverter;自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)
7:Automatic registration of MessageCodesResolver
(see below).定义错误代码生成规则
8:Automatic use of a ConfigurableWebBindingInitializer
bean (see below).
- 我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)
**org.springframework.boot.autoconfigure.web:web的所有自动场景;**
If you want to keep Spring Boot MVC features, and you just want to add additional [MVC configuration](https://docs.spring.io/spring/docs/4.3.14.RELEASE/spring-framework-reference/htmlsingle#mvc) (interceptors, formatters, view controllers etc.) you can add your own `@Configuration` class of type `WebMvcConfigurerAdapter`, but **without** `@EnableWebMvc`. If you wish to provide custom instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter` or `ExceptionHandlerExceptionResolver` you can declare a `WebMvcRegistrationsAdapter` instance providing such components.
If you want to take complete control of Spring MVC, you can add your own `@Configuration` annotated with `@EnableWebMvc`.
4.2:扩展MVC
以前用mvc的时候是这样用的
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
现在SpringBoot是这样用的:
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;2.x后直接实现WebMvcConfigurer接口
既保留了所有的自动配置,也能用我们扩展的配置;
/**
* Description:我们自己的配置类,//使用WebMvcConfigurer可以来扩展SpringMVC的功能
* Date: 2020/5/20 - 下午 3:59
* author: wangkanglu
* version: V1.0
*/
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /hello 请求来到 success页面
registry.addViewController("/hello").setViewName("success");
}
}
原理:
- WebMvcAutoConfiguration是SpringMVC的自动配置类
- 在做其他自动配置时会导入;@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的自动配置和我们的扩展配置都会起作用;
4.3:全面接管SpringMVC
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;
@EnableWebMvc
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /hello 请求来到 success页面
registry.addViewController("/hello").setViewName("success");
}
}
原理:
为什么@EnableWebMvc自动配置就失效了;
1:@EnableWebMvc的核心
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
2:DelegatingWebMvcConfiguration类
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3:WebMvcAutoConfiguration工作的原理
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
//当没有这个类的时候mvc的自动配置才生效
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
4:@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
5:导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
5:如何修改SpringBoot的默认配置
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
6:基于webmvc的RestfulCRUD实验
6.1:默认访问首页
注:在配置文件中添加项目名是
#项目名
server.servlet.context-path=/crud
6.2:国际化配置---中英文显示
springmvc使用的步骤:
1)、编写国际化配置文件;
2)、使用ResourceBundleMessageSource管理国际化资源文件
3)、在jsp页面使用fmt:message取出国际化内容
SpringBoot的使用步骤:
1:编写国际化配置文件,抽取页面需要的国际化信息
2:查看springboot的国际化配置原理
在配置文件中配置国际化文件的地址
3:去页面获取国际化的值(用#{})
效果:根据浏览器的默认语言,来获取对应的字段
注:乱码的话设置properties文件为utf-8
4:根据链接切换国际化
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象); 默认的就是根据请求头带来的区域信息获取Locale进行国际化
我们自己配置自己的LocaleResolver,然后其抛出去用我们的不用系统的
6.3:登录
开发期间模板引擎页面修改以后,要实时生效
1)、禁用模板引擎的缓存---开发专用
# 禁用缓存
spring.thymeleaf.cache=false
2)、页面修改完成以后ctrl+f9:重新编译;
注:springboot中登录后的页面做成重定向;
先映射
再重定向
在页面利用thymleaf的if判断增加登录消息错误的提示
6.4:拦截器进行登录检查
1:将登录成功后的标识加入session中
2:自定义拦截器
3:注册拦截器(springboot1.x不用排除静态资源,但是2.x也屏蔽了静态资源,需要排除)
6.5:CRUD-员工列表
1)、RestfulCRUD:CRUD满足Rest风格;
URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作
2)、实验的请求架构;
6.6:thymeleaf公共页面元素抽取
1:springboot文档说明
1、抽取公共片段
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::#selector}:模板名::如id选择器选择器
~{templatename::fragmentname}:模板名::片段名
3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
2:三种引入公共片段的th属性:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
效果
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
3:例子:
片段名:
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
</li>
</ul>
</nav>
引入:
<!-- 引入topbar:-->
<div th:replace="~{commons/bar::topbar}"></div>
id选择器
<nav class="col-md-2 d-none d-md-block bg-light sidebar" id = "rightbar">
引入:
<!-- 引入sidebar -->
<div th:replace="commons/bar::#rightbar(activeUrl='main.html')"></div>
4:向引入的片段中传参数
6.7:CRUD-员工添加
//return"/emps";表示来到thymleaf引擎下的这个页面
//return"redirect:/emps";表示重定向到一个地址,“/”表示当前项目下
//return"forward:/emps";表示转发到一个地址
注:
提交的数据格式不对:生日:日期;
格式有:2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;默认日期是按照/的方式;
如果需要更改格式化需要在配置文件中配置:
#更改日期格式
spring.mvc.format.date=yyyy-MM-dd
6.8:CRUD-员工修改
resful接口,读取路径中的参数
修改员工页面和添加员工页面二合一(主要是thymleaf的用法)
<!--需要区分是员工修改还是添加;-->
<form th:action="@{/emp}" method="post">
<!--发送put请求修改员工数据-->
<!--
1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
2、页面创建一个post表单
3、创建一个input项,name="_method";值就是我们指定的请求方式
-->
<input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>
<input type="hidden" name="id" th:value="${emp!=null}?${emp.id}" th:if="${emp!=null}"/>
<div class="form-group">
<label>LastName</label>
<input type="text" name="lastName" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id">
<option th:selected="${emp!=null}?${department.id==emp.department.id}" th:value="${department.id}" th:text="${department.departmentName}"
th:each="department:${departments}">1
</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" name="birth" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}">
</div>
<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
</form>
注:springboot2.x版本后开启put接口的拦截器要打开
#开启springboot的put模式
spring.mvc.hiddenmethod.filter.enabled=true
6.9:CRUD-员工删除
<td>
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<button id="deletebtn" th:attr="dele_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
<form id="deleteEmpForm" method="post">
<input type="hidden" name="_method" value="delete"/>
</form>
<script>
$("#deletebtn").click(function () {
// alert(1)
$("#deleteEmpForm").attr("action",$(this).attr("dele_uri")).submit();
});
</script>
注:同时也记得在配置文件中配置:
spring.mvc.hiddenmethod.filter.enabled=true
7:错误处理的机制
7.1:SpringBoot默认的错误处理机制
1:浏览器,默认返回一个页面
请求头:
2:如果是其他客户端访问返回json数据
请求头:
7.2:springboot的错误机制原理
可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;
步骤:
1:一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);
系统出现错误以后来到/error请求进行处理;(相当于web.xml注册的错误页面规则)
2:来到/error请求;就会被BasicErrorController处理;处理默认的/error请求
这个类的代码是:
@RequestMapping(
//返回html页面,浏览器请求来到这个请求
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//通过这个方法来到错误页面
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
//返回json数据,其他客户端来到这个请求
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
//当ResponseEntity的数据为list,map之类的话,自动转为json
return new ResponseEntity(body, status);
}
}
3:上述跳转错误页面的方法resolveErrorView解析如下:
//所有的ErrorViewResolver得到ModelAndView,去哪个页面是由DefaultErrorViewResolver解析得到的;
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
Iterator var5 = this.errorViewResolvers.iterator();
ModelAndView modelAndView;
//所有的ErrorViewResolver得到ModelAndView
do {
if (!var5.hasNext()) {
return null;
}
ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
//通过这个方法来到DefaultErrorViewResolver
modelAndView = resolver.resolveErrorView(request, status, model);
} while(modelAndView == null);
return modelAndView;
}
4:如果模板引擎可用就来到如:/error/404.html,如果不存在就在静态资源中寻找404.html
7.3:定制错误响应-定制错误页面
注:springboot2.x后默认不显示message和excption需要在配置文件中配置
#提示message消息
server.error.include-message=always
#显示excepting消息
server.error.include-exception=true
1)、有模板引擎的情况下;error/状态码;
【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
当跳转错误页面时,会向页面带错误信息,该信就由下边的 方法得到:
所以页面能获取的信息;
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
前台展示:
<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>error:[[${error}]]</h2>
<h2>exception:[[${exception}]]</h2>
<h2>message:[[${message}]]</h2>
<h2>errors:[[${errors}]]</h2>
7.4:定制错误响应-定制错误json数据
1:自定义异常处理,返回定制的json数据;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotException.class)
public Map<String,Object> handldeException(Exception e){
Map<String ,Object> map = new HashMap<>();
map.put("code","usernotfind");
map.put("message",e.getMessage());
return map;
}
}
弊端就是这个方法没有自适应效果,不论是客户端还是浏览器都返回该json数据;
2:转发到/error进行自适应响应效果处理
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UserNotException.class)
public String handldeException(Exception e, HttpServletRequest request){
Map<String ,Object> map = new HashMap<>();
// Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
//传入我们自己的状态码
request.setAttribute("javax.servlet.error.status_code",400);
map.put("code","usernotfind");
map.put("message",e.getMessage());
System.out.println("e:"+ JSONObject.toJSONString(e));
return "forward:/error";
}
}
7.5:定制错误响应-将我们的数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1:所以我们可以完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中; 但是太费时 不推荐
2:页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;是DefaultErrorAttributes的方法,所以我们可以重写DefaultErrorAttributes类的方法
@Component
public class MyErrorContoller extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> map = super.getErrorAttributes(webRequest, options);
//增加我们自己的标识
map.put("sign","wkl");
//或者从请求域中拿到我们跑出异常的信息(该信息事前放在请求域中)
//他的构造方法,0代表request请求域,1代表session
Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}
8:配置嵌入式Servlet容器
Springboot默认使用Tomcat作为嵌入式的容器
8.1:如何定制和修改Sevlet容器的相关配置
1:配置文件修改和server有关的配置(ServerProperties);
server.port=8081
server.context-path=/crud
server.tomcat.uri-encoding=UTF-8
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx
2:编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
@Bean
public ConfigurableServletWebServerFactory configurableServletWebServerFactory(){
TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory();
tomcatServletWebServerFactory.setPort(8089);
return tomcatServletWebServerFactory;
}
8.2:注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。
注册三大组件用以下方式
1:ServletRegistrationBean
@Configuration
public class MyServletConfig {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/servlet");
return servletRegistrationBean;
}
}
2:FilterRegistrationBean
public class MyFileter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("MyFilter process...");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
//注册Filter
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new MyFileter());
filterRegistrationBean.setUrlPatterns(Arrays.asList("/servlet"));
return filterRegistrationBean;
}
3:ServletListenerRegistrationBean
//监听服务器启动关闭
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contenx监听器启动了。。。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contenx监听器关闭了。。。");
}
}
//注册监听器
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean(new MyListener());
return servletListenerRegistrationBean;
}
4:SpringBoot帮我们自动配置SpringMVC的时候,自动的注册SpringMVC的前端控制器;DIspatcherServlet;
在DispatcherServletAutoConfiguration类中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(
DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet, this.serverProperties.getServletMapping());
//默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp
//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径
registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
registration.setLoadOnStartup(
this.webMvcProperties.getServlet().getLoadOnStartup());
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
return registration;
}
8.3:替换为其他嵌入式Servlet容器
默认支持:
Tomcat(默认使用)
<!--引入web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Jetty(长链接如聊天)
<!-- 引入web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入其他sevrlet容器 -->
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
Undertow(不支持jsp)
<!-- 引入web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入其他sevrlet容器 -->
<dependency>
<artifactId>spring-boot-starter-undertow</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
8.4:嵌入式Servlet容器自动配置原理;
步骤:
1)、SpringBoot根据导入的依赖情况,给容器中添加相应的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
2)、容器中某个组件要创建对象就会惊动后置处理器;EmbeddedServletContainerCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;
3)、后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法
8.5:嵌入式Servlet容器启动原理;
什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;
获取嵌入式的Servlet容器工厂:
1)、SpringBoot应用启动运行run方法
2)、refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个组件】;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则:AnnotationConfigApplicationContext
3)、refresh(context);刷新刚才创建好的ioc容器;
4)、 onRefresh(); web的ioc容器重写了onRefresh方法
5)、webioc容器会创建嵌入式的Servlet容器;createEmbeddedServletContainer();
6)、获取嵌入式的Servlet容器工厂:
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
从ioc容器中获取EmbeddedServletContainerFactory 组件;TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;
7)、使用容器工厂获取嵌入式的Servlet容器:this.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer());
8)、嵌入式的Servlet容器创建对象并启动Servlet容器;
先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来;
IOC容器启动创建嵌入式的Servlet容器
9、使用外置的Servlet容器
嵌入式Servlet容器:应用打成可执行的jar
优点:简单、便携;
缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂【EmbeddedServletContainerFactory】);
外置的Servlet容器:外面安装Tomcat---应用war包的方式打包;
9.1:步骤:
1:必须创建一个war项目;
2:利用idea创建好目录结构(创建webapp目录和web.xml)
创建webapp目录
创建web.xml
3:将嵌入式的Tomcat指定为provided;
4:必须编写一个SpringBootServletInitializer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//传入SpringBoot应用的主程序
return application.sources(Springboot04WebJspApplication.class);
}
}
5:配置外部tomcat
6:测试路径
#跳转页面前缀
spring.mvc.view.prefix=/WEB-INF/
#跳转页面后缀
spring.mvc.view.suffix=.jsp
9.2:原理
jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;
war包:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器;
规则:
1)、服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
2)、ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名
3)、还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;
9.3:过程
1)、启动Tomcat
2)、org/springframework/spring-web/5.2.6.RELEASE/spring-web-5.2.6.RELEASE.jar!/META-INF/services/javax.servlet.ServletContainerInitializer
Spring的web模块里面有这个文件,内容:org.springframework.web.SpringServletContainerInitializer
3:SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set<Class<?>>;为这些不是接口的WebApplicationInitializer类型的类创建实例;
4:每一个WebApplicationInitializer都调用自己的onStartup;
他的实现类:
5:相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法,该方法就是ServletInitializer的父类
6:SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建根容器
protected WebApplicationContext createRootApplicationContext(
ServletContext servletContext) {
//1、创建SpringApplicationBuilder环境构建器
SpringApplicationBuilder builder = createSpringApplicationBuilder();
StandardServletEnvironment environment = new StandardServletEnvironment();
environment.initPropertySources(servletContext, null);
builder.environment(environment);
builder.main(getClass());
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(
new ServletContextApplicationContextInitializer(servletContext));
builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
//调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
builder = configure(builder);
//使用builder创建一个Spring应用
SpringApplication application = builder.build();
if (application.getSources().isEmpty() && AnnotationUtils
.findAnnotation(getClass(), Configuration.class) != null) {
application.getSources().add(getClass());
}
Assert.state(!application.getSources().isEmpty(),
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Ensure error pages are registered
if (this.registerErrorPageFilter) {
application.getSources().add(ErrorPageFilterConfiguration.class);
}
//启动Spring应用
return run(application);
}
7:Spring的应用就启动并且创建IOC容器
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//刷新IOC容器
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}