SpringBoot与Web开发
Posted Young_Yang_Yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot与Web开发相关的知识,希望对你有一定的参考价值。
1.简介
使用SpringBoot;
1.创建SpringBoot应用,选中我们需要的模块
2.SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3.自己编写业务代码
自动配置原理?
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?
1 xxxAutoConfiguration:帮我们给容器中自动配置组件 2 xxxProperties:配置类来封装配置文件的内容
//可以设置和静态资源有关的参数,缓存时间
2.SpringBoot对静态资源的映射规则;
1 @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) 2 public class ResourceProperties implements ResourceLoaderAware { 3 //可以设置和静态资源有关的参数,缓存时间等
1 @Override 2 public void addResourceHandlers(ResourceHandlerRegistry registry) { 3 if (!this.resourceProperties.isAddMappings()) { 4 logger.debug("Default resource handling disabled"); 5 return; 6 } 7 Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); 8 CacheControl cacheControl = this.resourceProperties.getCache() 9 .getCachecontrol().toHttpCacheControl(); 10 if (!registry.hasMappingForPattern("/webjars/**")) { 11 customizeResourceHandlerRegistration(registry 12 .addResourceHandler("/webjars/**") 13 .addResourceLocations("classpath:/META-INF/resources/webjars/") 14 .setCachePeriod(getSeconds(cachePeriod)) 15 .setCacheControl(cacheControl)); 16 } 17 String staticPathPattern = this.mvcProperties.getStaticPathPattern(); 18 if (!registry.hasMappingForPattern(staticPathPattern)) { 19 customizeResourceHandlerRegistration( 20 registry.addResourceHandler(staticPathPattern) 21 .addResourceLocations(getResourceLocations( 22 this.resourceProperties.getStaticLocations())) 23 .setCachePeriod(getSeconds(cachePeriod)) 24 .setCacheControl(cacheControl)); 25 } 26 }
1.所有/webjars/**,都去classpath:/META-INF/resources/webjar/找资源;
webjars:以jar包的方式引入静态资源
localhost:8080/jquery/3.3.1/jquery.js
<!-- 引入jquery-webjar -->在访问的时候只需要写webjars下面资源的名称即可 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
2."/**"访问当前项目的任何资源,(静态资源的文件夹)
1 "classpath:/META-INF/resources/", 2 "classpath:/resources/", 3 "classpath:/static/", 4 "classpath:/public/" 5 "/":当前项目的根路径
localhost:8080/abc ===> 去静态资源文件夹里面找abc
3.欢迎页;静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
4.所有的**/favicon.ico 都是在静态资源文件夹找
3.模板引擎
jsp、Velocity、Thymeleaf
SpringBoot推荐的Thymeleaf
语法更简单,功能更强大
1.引入thymeleaf
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-thymeleaf</artifactId> 4 </dependency>
切换thymeleaf版本
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 --> <!-- thymeleaf2 layout1 --> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
2.Thymeleaf使用&语法
1 @ConfigurationProperties(prefix = "spring.thymeleaf") 2 public class ThymeleafProperties { 3 4 private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; 5 6 public static final String DEFAULT_PREFIX = "classpath:/templates/"; 7 8 public static final String DEFAULT_SUFFIX = ".html";
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染
使用:
1.导入thymeleaf的名称空间
1 <html lang="en" xmlns:th="http://www.thymeleaf.org">
2.使用thymeleaf语法
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>成功!</h1> 9 <!-- th:text 将div里面的文本内容设置为 --> 10 <div th:text="${hello}"></div> 11 </body> 12 </html>
3.语法规则
1.th:text;改变当前元素里面的文本内容
th:任意html属性;来替换原生属性的值
2.表达式
1 Simple expressions:(表达式语法) 2 Variable Expressions: ${...}:获取变量值;OGNL; 3 1)、获取对象的属性、调用方法 4 2)、使用内置的基本对象: 5 #ctx : the context object. 6 #vars: the context variables. 7 #locale : the context locale. 8 #request : (only in Web Contexts) the HttpServletRequest object. 9 #response : (only in Web Contexts) the HttpServletResponse object. 10 #session : (only in Web Contexts) the HttpSession object. 11 #servletContext : (only in Web Contexts) the ServletContext object. 12 13 ${session.foo} 14 3)、内置的一些工具对象: 15 #execInfo : information about the template being processed. 16 #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax. 17 #uris : methods for escaping parts of URLs/URIs 18 #conversions : methods for executing the configured conversion service (if any). 19 #dates : methods for java.util.Date objects: formatting, component extraction, etc. 20 #calendars : analogous to #dates , but for java.util.Calendar objects. 21 #numbers : methods for formatting numeric objects. 22 #strings : methods for String objects: contains, startsWith, prepending/appending, etc. 23 #objects : methods for objects in general. 24 #bools : methods for boolean evaluation. 25 #arrays : methods for arrays. 26 #lists : methods for lists. 27 #sets : methods for sets. 28 #maps : methods for maps. 29 #aggregates : methods for creating aggregates on arrays or collections. 30 #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration). 31 32 Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样; 33 补充:配合 th:object="${session.user}: 34 <div th:object="${session.user}"> 35 <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> 36 <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 37 <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> 38 </div> 39 40 Message Expressions: #{...}:获取国际化内容 41 Link URL Expressions: @{...}:定义URL; 42 @{/order/process(execId=${execId},execType=\'FAST\')} 43 Fragment Expressions: ~{...}:片段引用表达式 44 <div th:insert="~{commons :: main}">...</div> 45 46 Literals(字面量) 47 Text literals: \'one text\' , \'Another one!\' ,… 48 Number literals: 0 , 34 , 3.0 , 12.3 ,… 49 Boolean literals: true , false 50 Null literal: null 51 Literal tokens: one , sometext , main ,… 52 Text operations:(文本操作) 53 String concatenation: + 54 Literal substitutions: |The name is ${name}| 55 Arithmetic operations:(数学运算) 56 Binary operators: + , - , * , / , % 57 Minus sign (unary operator): - 58 Boolean operations:(布尔运算) 59 Binary operators: and , or 60 Boolean negation (unary operator): ! , not 61 Comparisons and equality:(比较运算) 62 Comparators: > , < , >= , <= ( gt , lt , ge , le ) 63 Equality operators: == , != ( eq , ne ) 64 Conditional operators:条件运算(三元运算符) 65 If-then: (if) ? (then) 66 If-then-else: (if) ? (then) : (else) 67 Default: (value) ?: (defaultvalue) 68 Special tokens: 69 No-Operation: _
4.SpringMVC自动配置
1. Spring MVC auto-configuration
Spring Boot自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认:
A.Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans
自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向))
ContentNegotiatingViewResolver :组合所有的视图解析器的;
如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来
B.Support for serving static resource,including support for Webjars(see below).静态资源文件家路径webjars
C.Static index.html support.静态首页访问
D.Custom Fvicon support(see below).favicon.ico
E.自动注册了 Converter,GenericConverter,Formatter beans
Converter:转换器;public String hello(User user):类型转换使用Converter
Formatter:格式化器;2017-12-17===Date;
@Bean @Override public FormattingConversionService mvcConversionService() { WebConversionService conversionService = new WebConversionService( this.mvcProperties.getDateFormat()); addFormatters(conversionService); return conversionService; }
自己添加的格式化器转换器,我们只需要放在容器中即可
F.Support for HttpMessageConverters(see below).
HttpMessageConverter:SpirngMVC用来转换Http请求和响应的;User---json;
HttpMessageConverters是从容器中确定;获取所有的HttpMessageConverter;
自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)
G.MessageCodesResolver
定义错误代码生成规则
H.ConfigurableWebBindingInitializer
我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)
1 初始化WebDataBinder;
2 请求数据=====JavaBean;
org.springframework.boot.autoconfigure.web:web的所有自动场景;
2. 扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/hello"/> <bean></bean> </mvc:interceptor> </mvc:interceptors>
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc
即保留了所有的自动配置,也能用我们扩展的配置
1 //使用WebMvcConfigurerAdapter可以扩展SpringMVC的功能 2 @Configuration 3 public class MyMvcConfig extends WebMvcConfigurerAdapter { 4 5 @Override 6 public void addViewControllers(ViewControllerRegistry registry) { 7 //super.addViewControllers(registry); 8 //浏览器发送 /young 请求,来到success页面 9 registry.addViewController("/young").setViewName("success"); 10 } 11 }
原理:
1.WebMvcAutoConfiguration是SpingMVC的自动配置类
2.在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
1 @Configuration 2 public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration { 3 private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); 4 5 //从容器中获取所有的WebMvcConfigurer 6 @Autowired(required = false) 7 public void setConfigurers(List<WebMvcConfigurer> configurers) { 8 if (!CollectionUtils.isEmpty(configurers)) { 9 this.configurers.addWebMvcConfigurers(configurers); 10 //一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用; 11 @Override 12 // public void addViewControllers(ViewControllerRegistry registry) { 13 // for (WebMvcConfigurer delegate : this.delegates) { 14 // delegate.addViewControllers(registry); 15 // } 16 } 17 } 18 }
3.容器中所有的WebMvcConfigurer 都会一起起作用
4.我们的配置类也会被调用
效果:SpringMVC的自动配置和我们的扩展配置都会起作用
3. 全面接管SpringMVC
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;
1 //使用WebMvcConfigurerAdapter可以扩展SpringMVC的功能 2 @EnableWebMvc 3 @Configuration 4 public class MyMvcConfig extends WebMvcConfigurerAdapter { 5 6 @Override 7 public void addViewControllers(ViewControllerRegistry registry) { 8 //super.addViewControllers(registry); 9 //浏览器发送 /young 请求,来到success页面 10 registry.addViewController("/young").setViewName("success"); 11 } 12 }
原理:
为什么@EnableWebMvc自动配置就失效了?
1.EnableWebMvc的核心
1 @Import(DelegatingWebMvcConfiguration.class) 2 public @interface EnableWebMvc { 3 }
2.
1 @Configuration 2 public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3.
1 @Configuration 2 @ConditionalOnWebApplication(type = Type.SERVLET) 3 @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) 4 //容器中没有这个组件的时候,这个自动配置类才生效 5 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) 6 @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) 7 @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, 8 ValidationAutoConfiguration.class }) 9 public class WebMvcAutoConfiguration {
4.@EnableWebMvc将WebMvcConfigurationSupport这个组件导入进来了;
5.导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
5.如何修改SpringBoot的默认配置
模式:
1.SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2.在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3.在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
6.RestfulCRUD
1.默认访问首页
1 //使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能 2 //@EnableWebMvc 不要接管SpringMVC 3 @Configuration 4 public class MyMvcConfig extends WebMvcConfigurerAdapter { 5 6 @Override 7 public void addViewControllers(ViewControllerRegistry registry) { 8 // super.addViewControllers(registry); 9 //浏览器发送 /atguigu 请求来到 success 10 registry.addViewController("/atguigu").setViewName("success"); 11 } 12 13 //所有的WebMvcConfigurerAdapter组件都会一起起作用 14 @Bean //将组件注册在容器 15 public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ 16 WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { 17 @Override 18 public void addViewControllers(ViewControllerRegistry registry) { 19 registry.addViewController("/").setViewName("login"); 20 registry.addViewController("/index.html").setViewName("login"); 21 } 22 }; 23 return adapter; 24 } 25 }
2.国际化
1.编写国际化配置文件
2.使用ResourceBundleMessageSource管理国际化资源文件
3.在页面使用fmt:message取出国家化内容
步骤:
1.编写国家化配置文件,抽取页面需要显示的国家化消息
2.SpringBoot自动配置好了管理国际化资源文件的组件
1 @ConfigurationProperties(prefix = "spring.messages") 2 public class MessageSourceAutoConfiguration { 3 4 /** 5 * Comma-separated list of basenames (essentially a fully-qualified classpath 6 * location), each following the ResourceBundle convention with relaxed support for 7 * slash based locations. If it doesn\'t contain a package qualifier (such as 8 * "org.mypackage"), it will be resolved from the classpath root. 9 */ 10 private String basename = "messages"; 11 //我们的配置文件可以直接放在类路径下叫messages.properties; 12 13 @Bean 14 public MessageSource messageSource() { 15 ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 16 if (StringUtils.hasText(this.basename)) { 17 //设置国际化资源文件的基础名(去掉语言国家代码的) 18 messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray( 19 StringUtils.trimAllWhitespace(this.basename))); 20 } 21 if (this.encoding != null) { 22 messageSource.setDefaultEncoding(this.encoding.name()); 23 } 24 messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale); 25 messageSource.setCacheSeconds(this.cacheSeconds); 26 messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat); 27 return messageSource; 28 }
3.去页面获取国际化的值
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 6 <meta name="description" content=""> 7 <meta name="author" content=""> 8 <title>Signin Template for Bootstrap</title> 9 <!-- Bootstrap core CSS --> 10 <link href="asserts/css/bootstrap.min.css" th:hrefSpringBoot -- SpringBoot与Web开发