一、Web 开发
自动配置原理:
xxxAutoConfiguration: 帮助我们给容器中自动配置组件;
xxxProperyties: 配置类来
1、 SpringBoot对静态资源的映射规则
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
// 可是设置和静态资源有关的参数,缓存时间等
WebMvcAuotConfiguration:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**")
.addResourceLocations(
"classpath:/META‐INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
// 静态资源文件夹的映射
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(
this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
// 配置欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
ResourceProperties resourceProperties) {
return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
// 配置喜欢的图标
@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;
}
}
-
所有的/webjars/**,都去classpath:/META-INF/resources/web/找资源
webjars :以jar包的方式引入静态资源;http://www.webjars.org/
导入依赖:
<!--引入jquery-webjar 访问的时候只需要写webjars下面的资源名称即可-->
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
**测试:**localhost:8080/webjars/jquery/3.3.1/dist/jquery.js
- “/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射。
- “classpath:/META-INF/resources/”
- “classpath:/resources/”
- “classpath:/static/”
- “classpath:/public/”
- “/”:当前项目
例如: localhost:8080/abc == 去静态资源文件夹里面找abc
-
欢迎页: 静态资源文件下的所有index.html 页面;被"/**"映射
-
所有的 **/favicaon.ico 都是在静态资源文件下找
2、引擎模板
jsp、velocity、Freemarker、Thymeleaf
SpringBoot推荐的Tymeleaf,语法更简单,功能更强大;
① 引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
测试:
@RequestMapping(value = "/success")
public String success(){
return "success";
}
切换thymeleaf版本
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
启动报错:
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateEngine(ThymeleafAutoConfiguration.java:142)
The following method did not exist:
解决方案:
<properties>
<springboot-thymeleaf.version>3.0.9.RELEASE</springboot-thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
原因分析:
这里用的org.springframework.boot下的spring-boot-starter-thymeleaf,使用<thymeleaf.version>做标签时的可能与org.thymeleaf头冲突,导致包获取不正确。
② Thymeleaf使用
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
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页面的放在classpath:/templates/, thymeleaf 就能自动渲染。
使用:
- 导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 使用thymeleaf语法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>success 测试成功</h1>
<div th:text="${hello}"></div>
</body>
</html>
③ 语法规则
-
th:text: 改变当前元素里面的内容。
th: 任意html属性;来替换原生的值。
- 表达式
Simple expression: (表达式语法)
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: _
3、SpringMVC自动配置
可以参考文档:https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developingweb-applications
① Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot 对SpringMVC的默认配置:(WebMvcAutoConfiguration)
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自动配置ViewResource(视图解析器:根据方法的返回值得视图对象的(View), 视图对象决定如何渲染(转发?重定向?))
- ContextNegotiatingViewResolver: 组合所有的视图解析器的;
- 如何定制:我们可以给自己容器中添加一个视图解析器;自动的将其组合进来;
-
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
bean- Converter: 转换器;public String hello(User user): 类型转换使用 Converter
- Formatter 格式化器: 2020.8.29 == Date;
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date‐format")//在文件中配置日期格
式化的规则
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件
}
自己添加的格式化器转换器,我们只需要放在容器中即可
-
Support for HttpMessageConverters (see below)
-
HttpMessageConverter: SpringMVC用来转换Http请求和响应的 :User—json;
-
HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter;
给自己的容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean, @Component)
-
-
Automatic registration of
MessageCodesResolver
(see below). 定义错误的代码生成规则 -
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
我们可以配置一个ConfigurableWebBindingInitialzer 来替换默认的:(添加到容器)
初始化WebDataBinder;
请求数据=====JavaBean;
org.springframework.boot.autoconfigure.web的所有的自动场景;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration(interceptors, formatters, view controllers etc.) you can add your own @Configuration
class of typeWebMvcConfigurerAdapter
, 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
.
② 扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
编写一个配置类(@Configuration),是WebMvcConfigAdapter类型;不能标注@EnableWebMVC
既保留所有的自动配置,也能用我们扩展的配置;
注:WebMvcConfigurerAdapter该方法在spring boot 2.0,Spring 5.0 之后,已经被废弃
// 使用WebMvcConfigurer可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
// 浏览器发送 /oy 请求到 success
registry.addViewController("/oy").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);
// }
}
-
容器中所有的WebMvcConfigurer都会一起起作用
-
我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
③、全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;
// 使用WebMvcConfigurer可以来扩展SpringMVC的功能
@Configuration
@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
/* super.addViewControllers(registry);*/
// 浏览器 /oy 请求来到 success
registry.addViewController("/oy").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 {
- @EnableWebMvc将WebMvcConfiguationSupport组件导入进来
- 导入的WebMvcConfiguration只是SpringMVC最基本功能;
5、如何修改SpringBoot的默认设置
模式:
- SpringBoot在自动配置很多组件的时候,先看容器中有没有自己配置的(@Bean、@Component)如果有就用户自己配置,如果没有,才自动配置和自己默认组合起来;
- 在SpringBoot中国会有非常多的xxxConfigurer帮助我们进行扩展配置
- 在SpringBoot中会有很多的xxxCustomize帮助我们进行定制配置
6、RestfulCRUD
配置pom配置文件:
<properties>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<springboot-thymeleaf.version>3.0.9.RELEASE</springboot-thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
<!--配置thymeleaf模板-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
</dependencies>
① 默认访问首页
方式一:(不推荐)
// 在Controller中配置
@RequestMapping({"/","/index.html"})
public String index(){
return "index";
}
方式二:(推荐)
// 使用WebConfigurerAdapter可以来扩展SpringMVC的功能
// 使用@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送得 /oy 请求来到 success
registry.addViewController("/oy").setViewName("success");
}
// 所有的webMvcConfigAdapter组件都会一起起作用
@Bean // 将组件注册在容器
public MyMvcConfig MyMvcConfig1(){
MyMvcConfig config = new MyMvcConfig(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
return config;
}
}
【application.properties】
server.servlet.context-path=/curd
测试:
提前在POM.xml文件中引入bootstrap依赖(后面需要)
<!--引入bootstrap-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
② 国际化
-
编写国际化配置文件:
-
SpringBoot自动配置好了管理国际化资源文件的组件(2.x版本):
@Bean
@ConfigurationProperties(
prefix = "spring.messages"
)
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
// 设置国际化资源文件的基础名(去掉语言国家代码的) messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
1.x 版本:
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma‐separated list of basenames (essentially a fully‐qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
//我们的配置文件可以直接放在类路径下叫messages.properties;
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource;
}
- 在application.properties 文件中配置:
#指定管理国际化资源文件
spring.messages.basename=i18n.login
- 去页面获取的国际化的值、
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
测试:(更改浏览器语言)
原理:
国际化Locale(区域信息对象); LocaleResolver(获取区域信息对象)
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties
.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
默认的就是根据请求头带来的区域信息Localhost进行国际化
- 点击切换国际化
【MyLocaleResolver.calss】
// 可以在连接上携带区域的信息
public class MyLocaleResolver implements LocaleResolver{
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty("_")){
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
【MyMvcConfig.class】
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
【login.html】
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
③ 登录
开发期间模板的引擎页面修改以后,要实时生效
- 禁用模板引擎的缓存
# 禁用缓存
spring.thymeleaf.cache=false
- 页面修改完成完成以后ctrl +f9 : 重新编译;
【MyLocaleResolver.class】
public class MyLocaleResolver implements LocaleResolver{
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
【LonginController.class】
@Controller
public class LonginController {
@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String passsword, Map<String , Object> map, HttpSession session){
if(!StringUtils.isEmpty(username) && "123456".equals(passsword)){
// 登陆成功,防止表单重复提交,可以重定向到主页
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else{
// 登录失败
map.put("msg","用户名密码错误");
return "login";
}
}
}
【MyMvcConfig.class】
@Bean
public MyMvcConfig MyMvcConfig1(){
MyMvcConfig config = new MyMvcConfig(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
};
return config;
}
登录错误提示消息
【login.html】
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
④ 拦截器进行登陆检查
拦截器:
/**
*@Description 登录检查
*@Author OY
*@Date 2020/9/3
*@Time 16:07
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null){
// 未登入,返回登录界面
request.setAttribute("msg","没有权限请先登陆");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
// 以登录,放行请求
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
注册拦截器:【MyMvcConfig.class】
注: 拦截器必须配置不拦截css样式,不然页面的css样式会失效
// 所有的webMvcConfig组件都会一起起作用
@Bean // 将组件注册在容器
public MyMvcConfig MyMvcConfig1(){
MyMvcConfig config = new MyMvcConfig(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
// 注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 静态资源: *.css , *.js
// SpringBoot已经做好了静态资源映射
/* registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/")
.excludePathPatterns("/index.html","/","/user/login","/asset/**","/webjars/**");*/
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html",
"/",
"/user/login","/static/**", "/webjars/**");
//
}
};
return config;
}
⑤ CRUD-员工列表
实验要求:
- RestfulCURD: CURD满足Rest风格;
URL:/ 资源名称 / 资源标识HTTP请求的方式区分对资源CRUD 操作
普通CURD(uri来区分操作) | RestfulCRUD | |
---|---|---|
查询 | getEmp | emp—GET |
添加 | addEmp?xxx | emp—POST |
修改 | updateEmp?id=xxx&xxx=xx | emp/{id}—PUT |
删除 | deleteEmp?id=1 | emp/{id}—DELETE |
- 实验的请求架构:
实验功能 | 请求URL | 请求方式 |
---|---|---|
查询所有员工 | emps | GET |
查询某个员工(来到修改页面) | emp/1 | GET |
来到添加页面 | emp | GET |
添加员工 | emps | POST |
来到修改页面(查出员工进行信息回显) | emp/1 | GET |
修改员工 | emp | PUT |
删除员工 | emp/1 | DELETE |
- 员工列表
thymeleaf公共页面元素的抽取
1、抽取公共片段
<div th:fragment=“copy”>
© 2011 The Good Thymes Virtual Grocery
</div>2、引入公共片段
<div th:insert="~{footer:: copy}">
~{templatename :: selector} : 模板名 :: 选择器
~{templatename :: fragmentname} : 模板名 :: 片段名
3、默认效果
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{};
行内写法可加上 :[[~{}]]; [[~{}]]
三种引入片段的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>
抽取出公共的页面【bar.html】:
<!--topbar-->
<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>
<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" href="#" th:href="@{/main.html}"
th:class="${activeUri=='main.html'?'nav-link active':'nav-link'}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
Dashboard <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
Products
</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="#" th:href="@{/emps}"
th:class="${activeUri=='emps'?'nav-link active':'nav-link'}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
</li>
.........
</nva>
引入(选择高亮):
<!--引入抽取的topbar-->
<!--模板名: 会使用thymeleaf的前后缀的配置规则进行解析-->
<div th:replace="commons/bar :: topbar"></div>
<!--引入sidebar-->
<div th:replace="commons/bar :: #sidebar(activeUri='main.html')"></div>
【EmployeeController.java】
@Autowired
EmployeeDao employeeDao;
/**
* 查询所有的员工列列表页面
* @return
*/
@GetMapping(value = "/emps")
public String list(Map<String, Object> map){
Collection<Employee> employees = employeeDao.getAll();
//放在请求域中
map.put("emps", employees);
// thymeleaf 默认就会拼串
// classpath:/templates/xxxx.html
return "emp/list";
}
使用thymeleaf 模板列出所有的员工信息【list.html】
// 修改这个两处地方
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td th:text="${emp.lastName}"></td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
<td>
<a class="btn btn-sm btn-primary" href="#">编辑</a>
<button class="btn btn-danger">删除</button>
</td>
</tr>
</tbody>
⑥ CRUD-员工添加
将【list.html】替换为:
替换前:
<h2>Section title</h2>
替换后:
<h2><a class="btn btn-sm btn-success" href="#" th:href="@{/emp}">员工添加</a></h2>
【EmployeeController.java】
@Autowired
DepartmentDao departmentDao;
@GetMapping("/emp")
public String toAddPage(Map<String, Object> map){
// 来到添加页面,查出所有的部门
Collection<Department> departments = departmentDao.getDepartments();
map.put("depts",departments);
return "emp/add";
}
在templates/emp新建页面【add.html】:
// 复制list.html 进行细微的修改,删除原<main>标签中的元素替换为以下的内容
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<form th:action ="@{/emp}" method="post">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" >
</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" >
<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" >
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<!--提交的是部门的id-->
<select class="form-control" name="department.id">
<option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" name="birth" class="form-control" placeholder="zhangsan">
</div>
<button type="submit" class="btn btn-primary" >添加</button>
</form>
</main>
【application.properties】
# 格式化时间
spring.mvc.format.date=yyyy-MM-dd
日期的格式化: SpringMVC将页面的提交的值需要转换为指定的类型;
例如:2017-12-12----Date; 类型转换,格式化;
默认日期的按照/的方式
【EmployeeController.java】
/**
* 获取添加页面的信息
*/
@PostMapping(value = "/emp")
public String addEmp(Employee employee){
System.out.println("保存到员工信息:" + employee);
// 保存员工信息
employeeDao.save(employee);
// redirect: 重定向一个到地址 / 代表当前项目的路径
// forward: 表示转发一个地址
return "redirect:/emps";
}
修改【list.html】中的gender
<td th:text="${emp.gender}==0?'女':'男'"></td>
效果:
⑦ 员工修改
先通过id查询修改员工的信息【EmployeeController.java】
/**
* 来到修改页面,查询员工信息,回显
*/
@GetMapping(value = "/emp/{id}")
public String toEditPage(@PathVariable("id") Integer id, Map<String, Object> map){
Employee employee = employeeDao.get(id);
map.put("emp",employee);
// 页面要显示所有部门的信息
Collection<Department> departments = departmentDao.getDepartments();
map.put("depts",departments);
return "emp/add";
}
修改添加二合一表单【list.html】
<!--引入抽取的topbar-->
<!--模板名: 会使用thymeleaf的前后缀的配置规则进行解析-->
<div th:replace="commons/bar::topbar"></div>
<div class="container-fluid">
<div class="row">
<!--引入sidebar-->
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<!--需要区分是员工修改还是添加;-->
<form th:action ="@{/emp}" method="post">
<!--发送put请求修改员工数据-->
<!--
1.SpringMVC中配置HiddenHttpMethodFiler;(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.id}" th:if="${emp != null}">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!= null}?${emp.lastName}">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="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>
<!--提交的是部门的id-->
<select class="form-control" name="department.id">
<option th:selected="${emp!=null}?${dept.id==emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">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>
</main>
</div>
</div>
获取修改的数据,后台进行处理【EmployeeController.class】
/**
* 修改员工的信息,需要提交员工的id
* @param employee
* @return
*/
@PutMapping(value = "/emp")
public String updateEmployees(Employee employee){
System.out.println("员工修改信息为:"+employee);
employeeDao.save(employee);
return "redirect:/emps";
}
⑧ 员工删除
【EmployeeController.java】
/**
* 员工删除
* @param id
* @return
*/
@DeleteMapping("/emp/{id}")
public String deleteEmployee(@PathVariable("id") Integer id){
System.out.println("需要删除员工的Id为:"+ id);
employeeDao.delete(id);
return "redirect:/emps";
}
【list.html】
- 修改button添加属性
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
- 添加form表单
<form id="deleteEmpForm" method="post">
<input type="hidden" name="_method" value="delete">
</form>
- 用jquery 来处理用户删除
// 添加th:src 防止js、bootstrat等无法获取资源
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.2.1/dist/jquery.js}"></script>
<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script>
<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script>
<script>
$('.deleteBtn').click(function () {
var $tr = $(this).parent().parent();
var name = $tr.children(':first').html();
// 删除员工,并进行友好提示
if(confirm("确定要用户ID为【"+name+"】删除吗?")){
$("#deleteEmpForm").attr("action",$(this).attr('del_uri')).submit();
// 取消元素的默认行为
return false;
}
return false;
});
</script>
- 异常处理(delete请求被拦截)
There was an unexpected error (type=Method Not Allowed, status=405)
解决方法:在SpringBoot配置文件中【application.properties】中配置
# 取消delete请求拦截
spring.mvc.hiddenmethod.filter.enabled=true
7、错误处理机制
① SpringBoot默认的错误处理机制
默认效果:
- 浏览器,返回一个默认的错误页面
浏览器发送的请求的请求头:
- 如果是其他客户端,默认响应一个josn数据
原理:可以参照ErrorMvcAutoConfiguration; 错误处理的自动配置;
给容器中添加一下组件
- . DefaultErrorAttributes;
帮助我们在页面共享信息;
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,boolean includeStackTrace)
{
Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
errorAttributes.put("timestamp", new Date());
addStatus(errorAttributes, requestAttributes);
addErrorDetails(errorAttributes, requestAttributes,includeStackTrace);
addPath(errorAttributes, requestAttributes);
return errorAttributes;
}
- .BasicErrorController: 处理默认的/error请求
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
@RequestMapping(produces = "text/html")// 产生html类型的数据;浏览器发送的请求来到这个方法处理
public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//去哪个页面作为错误页面;包含页面地址和页面内容
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
}
@RequestMapping
@ResponseBody // 产生json数据,其他客户端来这个方法处理
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
3).ErrorPageCustomizer:
@Value("${error.path:/error}")
private String path = "/error"; 系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)
4). DefaultErroViewResolver:
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status), model);
if (modelAndView == null &&SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//默认的SpringBoot可以去找到一个页面 error/404
String errorViewName = "error/" + viewName;
//模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider =this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
if (provider != null) {
//模模板引擎可用的情况下返回errorViewName指定的试图地址
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用,就在静态资源文件只夹下找errorView对应的页面 error/404.html
return resolveResource(errorViewName, model);
}
步骤:一旦系统出现4xx或者5xx之类的错误;ErrorPageCustmizer就会生效(定制错误的响应规则);就会来到/error请求;就会BasicErrorController处理;
- 响应页面;去哪个页面的DefaultErrorViewResolver解析得到的;
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
//所有的ErrorViewResolver得到ModelAndView
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request,status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
② 如果定制错误响应:
1). 如何定制错误的页面
1. 有模板引擎的情况下:error/状态码;【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件下】,发生此状态码的错误就会来到对应的页面;
我们可以使用4xx和5xx作为错误的文件名来匹配这种类型的所有的错误,精确优先(优先寻找精确的状态码.html);
页面能获取的信息:
- timestamp: 时间戳
- staus: 状态码
- error: 错误提示
- exception: 异常对象
- mesage: 异常消息
- errors: JSR303数据校验的错误都在这里
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h1>404</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>status:[[${status}]]</h2>
<h2>error:[[${error}]]</h2>
</main>
-
没有模板引擎(模板引擎找不到这个错误的页面),静态资源文件夹下找;
-
以上都都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
2).如何定制错误的json数据;
- 自定义异常处理&返回定制的json数据;
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String, Object> handleException(Exception e){
Map<String, Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
// 没有自适应效果
- 转到到/error进行自适应想响应的效果处理
public String handException(Exception e, HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
// 传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
// 转发到/error
return "forward:/error";
}
3).将我们的定制数据携带出去;
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
- 完全来编写一个ErrorController的实现类【或者编写AbstractErrorController的子类】,放在容器中;
- 页面上能用的数据,或者是Json返回的能用的数据都是通过errAttributes.getErrorAttributes得到,容器中DefaultErrorAttrutes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
// 给容器中加入我们自己的定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("company","oy");
return map;
}
}
最终效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,
8、配置嵌入式Servle容器
SpringBoot默认使用Tomcat作为嵌入式的Servlet容器;
① 定制和修改Servlet容器的相关配置;
- 修改和Servlet有关的配置(ServletProperties【也是EmbeddedServletContainerCustomizer】);
server.port=8081
server.context-path=/curd
server.tomcat.uri-encoding=UTF-8
// 通用的Servlet容器设置
server.xxx
// Tomcat的设置
server.tomcat
- 编写一个EmbeddedServerContainerCustomizer(2.x以上已经不支持),使用ConfigurableServletWebServerFactory:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
@Configuration
public class MySeverConfig {
@Bean // 一定要将这个定制器加入到容器中
public ConfigurableServletWebServerFactory webServerFactory(){
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort(8083);
return factory;
}
}
② 注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件
注册三大组件用以下的方式
- ServletRegistrationBean
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
- FilterRegistrationBean
@Bean
public FilterRegistrationBean myListener(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
- ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean mylistener(){
ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(new MyListener());
return registrationBean;
}
SpringBoot帮我们自动SpringMVC的时候,自动注册SpringMVC的前端控制器;DispartcherServlet;
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;
}
③ 替换为其他嵌入式Servlet容器
默认支持:
Tomcat(默认使用)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
引入web模块就是使用嵌入式的Tomcat作为Server容器
</dependency>
Jetty
<!--引入web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Undertow
<!--引入web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
④ 嵌入式Servlet容器自动配置原理(1.x 版本)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)
// 导入BeanPostProcessorsRegister : 给容器中导入一些主件
// 导入了EmbeddedServletContainnerCustomizerBeanPostcessor:
// 后置处理器:Bean初始化后(创建完对象,还没赋值)执行初始化工作
@Configuration
@ConditionalOnClass({ Servlet.class, Tomcat.class })//判断当前是否引入了Tomcat依赖
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search =
SearchStrategy.CURRENT)// 判断当前容器没有用户自定定义EmbedddServerContainerFactory: 嵌入式的Server容器工厂; 作用: 创建嵌入式的Server容器
public class EmbeddedServletContainerAutoConfiguration {
public static class EmbeddedTomcat {
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory()
{
return new TomcatEmbeddedServletContainerFactory();
}
}
/**
* Nested configuration if Jetty is being used.
*/
@Configuration
@ConditionalOnClass({ Servlet.class, Server.class, Loader.class,WebAppContext.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class,searchSearchStrategy.CURRENT)
public static class EmbeddedJetty {
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
return new JettyEmbeddedServletContainerFactory();
}
}
} 、
/**
* Nested configuration if Undertow is being used.
*/
@Configuration
@ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search =
SearchStrategy.CURRENT)
public static class EmbeddedUndertow {
@Bean
public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
}
- EmbeddedServletContainerFactory(嵌入式Servlet容器工厂)
public interface EmbeddedServletContainerFactory {
//获取嵌入式的Servlet容器
EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers);
}
- EmbeddedServerContainer:(嵌入式的Servlet容器)
- 以TomcatEmbeddedServletContainerFactory为例
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
//创建一个Tomcat
Tomcat tomcat = new Tomcat();
//配置Tomcat的基本环节
File baseDir = (this.baseDirectory != null ? this.baseDirectory: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
// 将配置好的Tomcat传入进入,返回一个EmbeddedServerContainer;并启动Tomcat服务器
return getTomcatEmbeddedServletContainer(tomcat);
}
- 我们对嵌入式容器的配置修改是怎么生效的
ServerProperties、EmbeddedServleContainerCustomizer
5.容器中导入了EmbeddedServletContainerCustomizerBeanPostProcessor
//初始化之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//如果当前初始化的是一个ConfigurableEmbeddedServletContainer类型的组件
if (bean instanceof ConfigurableEmbeddedServletContainer) {
//
postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
}
return bean;
}
private void postProcessBeforeInitialization(
ConfigurableEmbeddedServletContainer bean) {
//获取所有的定制器,调用每一个定制器的customize方法来给Servlet容器进行属性赋值;
for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
customizer.customize(bean);
}
}
private void postProcessBeforeInitialization(ConfigurableEmbeddedServletContainer bean) {
//获取所有的定制器,调用每一个定制器的customize方法来给Servlet容器进行属性赋值;
for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
customizer.customize(bean);
}
}
private Collection<EmbeddedServletContainerCustomizer> getCustomizers() {
if (this.customizers == null) {
// Look up does not include the parent context
this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>(
this.beanFactory
//从容器中获取所有这葛类型的组件:EmbeddedServletContainerCustomizer
//定制Servlet容器,给容器中可以添加一个EmbeddedServletContainerCustomizer类型的组件
.getBeansOfType(EmbeddedServletContainerCustomizer.class,false, false).values());
Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
this.customizers = Collections.unmodifiableList(this.customizers);
}
return this.customizers;
}
ServerProperties 也是定制器
步骤:
-
SpringBoot根据导入的依赖情况,给容器中添加相应的
EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactroy】
-
容器中某个组件要创建对象就会惊动后置处理器;
EmbeddedServletContainCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;
-
后置处理器,从容中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法
9、 嵌入式Servlet容器启动原理
获取嵌入式的Servlet容器工厂:
1. SpringBoot应用启动运行run方法
2. refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器,并初始化容器,创建容器中的每一个组件】;如果是web应用创建**AnnotainConfigEmbedderWebApplicationContext**;否则;AnnotaionConfigApplicationContext
3. refresh(context); **刷新刚才创建的ioc容器**;
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post‐processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non‐lazy‐init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization ‐ " +"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
} finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
-
onRefrsh(); web的ioc容器重写 onRefresh 方法
-
webioc容器会创建嵌入式的Servlet容器; createEmbeddedServletContainer();
-
获取嵌入式的Servlet 容器工厂
EmbeddedServletContionerFactory containerFactory = getEmbeddedServletContianFactory();
从容器中获取EmbeddedServletContian 组件;TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就能获取所有定制器来定制Servlet 容器的相关配置;
-
使用容器工厂获取嵌入式的Server容器:
this.embeddedServletContainer = containerFactory.getEmbeddedServletContainer(getSelfInitializer());
-
嵌入式的Servlet 容器创建对象并启动Server容器;
先启动嵌入式Servlet容器,再将ioc容器下没有创建出的对象获取出来;
IOC容器启动创建嵌入式的Servlet容器
10、使用外置的Servlet 容器
嵌入式Servle容器: 应用打成可执行的jar
优点:简单、便携
缺点:默认不支持JSP、优先定制比较复杂(使用定制器【ServerProperties、自定义EmbeddesdServletContianCustizer】, 自己编写嵌入式Servlet容器的创建工厂【EmbeddedServletContainerFactory 】)
外置Servlet容器:外面安装Tomcat – 应用war 包的方式打开;
步骤:
-
必须创建一个web项目;
参考博客:https://blog.csdn.net/qq_45738810/article/details/108509314
-
建入嵌入式的Tomcat指定的provided;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
- 必须编写一个SpringBootServletInitiallzer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBoot06WebServletApplication.class);
}
}
- 启动服务器就可以使用;
原理:
jar包: 执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;
war包: 启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器;
规则:
-
服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServerContainnerInitializer实例:
-
ServletContainerInitializer的实现放在jar包的META-INF/servies 文件下,有一个名为java
-
还可以使用@HandlesTypes,在应用启动的时候加载配置的类
流程:
-
启动Tomcat
-
D:\RepMaven\org\springframework\spring-web\5.2.8.RELEASE\spring-web-5.2.8.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer:
Spring的web模块里面的这个文件:org.springframework.web.SpringServletContainerInitializer
-
SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class )标注的所有这个类型的类都传入onStratup方法的Setup方法的<Set>; 为这些WebApplicationInitializer类型的类创建实例:
-
每一个WebApplicaionInitialzer都调用自己的onStarup;
- 相当于我们的SpringBootServletInitalizer的创建对象,并执行onStarup方法
- 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);
}
- 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);
}
}
xtApplicationContextInitializer(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容器
~~~java
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);
}
}
启动Servlet容器,再启动SpringBoot应用