springboot实现web开发
springboot实现web开发
1、SpringMVC⾃动配置概览
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(⼤多场景我们都⽆需⾃定义配置)
The auto-configuration adds the following features on top of Spring’s defaults:
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
内容协商视图解析器和BeanName视图解析器
Support for serving static resources, including support for WebJars (covered )).
静态资源(包括webjars)
Automatic registration of Converter, GenericConverter, and Formatter beans.
⾃动注册 Converter,GenericConverter,Formatter
Support for HttpMessageConverters (covered ).
⽀持 HttpMessageConverters (后来我们配合内容协商理解原理)
Automatic registration of MessageCodesResolver (covered ).
⾃动注册 MessageCodesResolver (国际化⽤)
Static index.html support.
静态index.html 页⽀持
Custom Favicon support (covered ).
⾃定义 Favicon
Automatic use of a ConfigurableWebBindingInitializer bean (covered ).
⾃动使⽤ ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)
If you want to keep those Spring Boot MVC customizations and make more (interceptors, formatters,
view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
不⽤@EnableWebMvc注解。使⽤ **@Configuration** + **WebMvcConfigurer** ⾃定义规则
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
声明 **WebMvcRegistrations** 改变默认底层组件
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of
@EnableWebMvc.
使⽤ @EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全⾯接管SpringMVC
简单功能分析
静态资源访问
静态资源⽬录
只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
访问的路径为 : 当前项⽬根路径/ + 静态资源名
原理: 静态映射/**。
请求进来,先去Controller看能不能处理。不能处理的所有请求⼜都交给静态资源处理器。静态资源也不到则响应404页⾯改变默认的静态资源路径(静态资源访问添加前缀)
spring:
mvc:
static-path-pattern: /res/**#在/res/下⾯的请求
resources:
static-locations:[classpath:/haha/]#在类路径下设置哪⼀个静态资源⽂件夹
静态资源访问前缀
默认⽆前缀
spring:
mvc:
static-path-pattern: /res/**
当前项⽬ + static-path-pattern + 静态资源名 = 静态资源⽂件夹下(localhost:8080/res/静态资源)
webjar(使⽤较少可以⽤来引⼊静态资源)
⾃动映射 //**
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
欢迎页的⽀持
springboot⽀持
静态资源路径下 index.html
可以配置静态资源路径
但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
spring:
#  mvc:
#    static-path-pattern: /res/**  这个会导致welcome page功能失效
resources:
static-locations:[classpath:/haha/]
controller能处理/index
⾃定义Favicon(⼩图标)
favicon.ico 放在静态资源⽬录下即可。
#  mvc:
#    static-path-pattern: /res/**  这个会导致 Favicon 功能失效
静态资源配置原理
SpringBoot启动默认加载 xxxAutoConfiguration 类(⾃动配置类)
SpringMVC功能的⾃动配置类 WebMvcAutoConfiguration,⽣效
[外链图⽚转存失败,源站可能有防盗链机制,建议将图⽚保存下来直接上传(img-51xQ9VYF-1626575563862)
(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210717110054823.png)]
@Configuration(proxyBeanMethods =false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE +10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {}
给容器中配置了什么
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
配置⽂件的相关属性和xxx进⾏了绑定。WebMvcProperties==spring.mvc、ResourceProperties==sources 配置类只有⼀个有参构造器
//有参构造器所有参数的值都会从容器中确定
//ResourceProperties resourceProperties;获取和sources绑定的所有的值的对象
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory Spring的beanFactory
//HttpMessageConverters 到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer 到资源处理器的⾃定义器。=========
//DispatcherServletPath
//ServletRegistrationBean  给应⽤注册Servlet、
public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
ObjectProvider<DispatcherServletPath> dispatcherServletPath,
ObjectProvider<ServletRegistrationBean<?>> servletRegistrations){
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
}
资源处理的默认规则
public void addResourceHandlers(ResourceHandlerRegistry registry){
if(!sourceProperties.isAddMappings()){
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod =Cache().getPeriod();
CacheControl cacheControl =Cache().getCachecontrol().toHttpCacheControl(); //webjars的规则
if(!registry.hasMappingForPattern("/webjars/**")){ customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
//
String staticPathPattern =StaticPathPattern();
if(!registry.hasMappingForPattern(staticPathPattern)){ customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.
addResourceLocations(StaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
下⾯的源码为默认的静态资源的4个路径
@ConfigurationProperties(prefix ="sources", ignoreUnknownFields =false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS ={"classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/","classpath:/public/"};
/**springmvc的注解有哪些
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
欢迎页的处理规则
HandlerMapping:处理器映射。保存了每⼀个Handler能处理哪些请求。
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider){
WelcomePageHandlerMapping welcomePageHandlerMapping =new WelcomePageHandlerMapping( new TemplateAvailabilityProviders(applicationContext), applicationContext,getWelcomePage(),
StaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));  welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern){
if(welcomePage.isPresent()&&"/**".equals(staticPathPattern)){
//要⽤欢迎页功能,必须是/**
logger.info("Adding welcome page: "+ ());
setRootViewName("forward:index.html");
}
else if(welcomeTemplateExists(templateAvailabilityProviders, applicationContext)){
// 调⽤Controller  /index
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}
springboot 请求参数处理
请求映射
rest使⽤与原理
@xxxMapping;
Rest风格⽀持(使⽤HTTP请求⽅式动词来表⽰对资源的操作)
以前:**/getUser获取⽤户/deleteUser删除⽤户/editUser修改⽤户/saveUser保存⽤户现在: /user *GET-*获取⽤户 *DELETE-*删除⽤户 *PUT-*修改⽤户 *POST-*保存⽤户
核⼼Filter;HiddenHttpMethodFilter
⽤法: 表单method=post,隐藏域 _method=put
SpringBoot中⼿动开启
扩展:如何把_method 这个名字换成我们⾃⼰喜欢的。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。