Web开发

Springboot2之Web开发场景模块 - 图6

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.

Springboot2之Web开发场景模块 - 图7Springboot2之Web开发场景模块 - 图8

  • 内容协商视图解析器和BeanName视图解析器
  • 静态资源(包括webjars)
    • Automatic registration of Converter, GenericConverter, and Formatter beans.
  • 自动注册 Converter,GenericConverter,Formatter
  • 支持 HttpMessageConverters (后来我们配合内容协商理解原理)
  • 自动注册 MessageCodesResolver (国际化用)
    • Static index.html support.
  • 静态index.html 页支持
  • 自定义 Favicon
  • 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)

    If you want to keep those Spring Boot MVC customizations and make more MVC customizations (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

2、简单功能分析

2.1、静态资源访问

1、静态资源目录

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
访问 : 当前项目根路径/ + 静态资源名

原理: 静态映射/**。
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

改变默认的静态资源路径

  1. spring:
  2. mvc:
  3. static-path-pattern: /res/**
  4. resources:
  5. static-locations: [classpath:/haha/]

2、静态资源访问前缀

默认无前缀

  1. spring:
  2. mvc:
  3. static-path-pattern: /res/**

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找

3、webjar

自动映射 /webjars/**
https://www.webjars.org/

  1. <dependency>
  2. <groupId>org.webjars</groupId>
  3. <artifactId>jquery</artifactId>
  4. <version>3.5.1</version>
  5. </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

2.2、欢迎页支持

  • 静态资源路径下 index.html

    • 可以配置静态资源路径
    • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问 ```yaml spring:

      mvc:

      static-path-pattern: /res/** 这个会导致welcome page功能失效

    resources: static-locations: [classpath:/haha/] ```

  • controller能处理/index

    2.3、自定义 Favicon

    favicon.ico 放在静态资源目录下即可。

    1. spring:
    2. # mvc:
    3. # static-path-pattern: /res/** 这个会导致 Favicon 功能失效

    2.4、静态资源配置原理

  • SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)

  • SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效

    1. @Configuration(proxyBeanMethods = false)
    2. @ConditionalOnWebApplication(type = Type.SERVLET)
    3. @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
    4. @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    5. @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
    6. @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
    7. ValidationAutoConfiguration.class })
    8. public class WebMvcAutoConfiguration {}
  • 给容器中配了什么。

    1. @Configuration(proxyBeanMethods = false)
    2. @Import(EnableWebMvcConfiguration.class)
    3. @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
    4. @Order(0)
    5. public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
  • 配置文件的相关属性和xxx进行了绑定。

  • WebMvcProperties==spring.mvc
  • ResourceProperties==spring.resources

    1、配置类只有一个有参构造器

    1. //有参构造器所有参数的值都会从容器中确定
    2. //ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
    3. //WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
    4. //ListableBeanFactory beanFactory Spring的beanFactory
    5. //HttpMessageConverters 找到所有的HttpMessageConverters
    6. //ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
    7. //DispatcherServletPath
    8. //ServletRegistrationBean 给应用注册Servlet、Filter....
    9. public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
    10. ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
    11. ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
    12. ObjectProvider<DispatcherServletPath> dispatcherServletPath,
    13. ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
    14. this.resourceProperties = resourceProperties;
    15. this.mvcProperties = mvcProperties;
    16. this.beanFactory = beanFactory;
    17. this.messageConvertersProvider = messageConvertersProvider;
    18. this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
    19. this.dispatcherServletPath = dispatcherServletPath;
    20. this.servletRegistrations = servletRegistrations;
    21. }

2、资源处理的默认规则

  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().getCachecontrol().toHttpCacheControl();
  9. //webjars的规则
  10. if (!registry.hasMappingForPattern("/webjars/**")) {
  11. customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
  12. .addResourceLocations("classpath:/META-INF/resources/webjars/")
  13. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  14. }
  15. //
  16. String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  17. if (!registry.hasMappingForPattern(staticPathPattern)) {
  18. customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
  19. .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
  20. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  21. }
  22. }
  1. spring:
  2. # mvc:
  3. # static-path-pattern: /res/**
  4. resources:
  5. add-mappings: false 禁用所有静态资源规则
  1. @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
  2. public class ResourceProperties {
  3. private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
  4. "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
  5. /**
  6. * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
  7. * /resources/, /static/, /public/].
  8. */
  9. private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

3、欢迎页的处理规则

  1. HandlerMapping:处理器映射。保存了每一个Handler能处理哪些请求。
  2. @Bean
  3. public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
  4. FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
  5. WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
  6. new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
  7. this.mvcProperties.getStaticPathPattern());
  8. welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
  9. welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
  10. return welcomePageHandlerMapping;
  11. }
  12. WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
  13. ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
  14. if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
  15. //要用欢迎页功能,必须是/**
  16. logger.info("Adding welcome page: " + welcomePage.get());
  17. setRootViewName("forward:index.html");
  18. }
  19. else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
  20. // 调用Controller /index
  21. logger.info("Adding welcome page template: index");
  22. setRootViewName("index");
  23. }
  24. }

4、favicon

3、请求参数处理

0、请求映射

1、rest使用与原理

  • @xxxMapping;
  • Rest风格支持(使用HTTP请求方式动词来表示对资源的操作

    • 以前:/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户
    • 现在: /user GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户
    • 核心Filter;HiddenHttpMethodFilter
      • 用法: 表单method=post,隐藏域 _method=put
      • SpringBoot中手动开启
    • 扩展:如何把_method 这个名字换成我们自己喜欢的。 ```java @RequestMapping(value = “/user”,method = RequestMethod.GET) public String getUser(){ return “GET-张三”; }

      @RequestMapping(value = “/user”,method = RequestMethod.POST) public String saveUser(){ return “POST-张三”; }

  1. @RequestMapping(value = "/user",method = RequestMethod.PUT)
  2. public String putUser(){
  3. return "PUT-张三";
  4. }
  5. @RequestMapping(value = "/user",method = RequestMethod.DELETE)
  6. public String deleteUser(){
  7. return "DELETE-张三";
  8. }
  9. @Bean
  10. @ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
  11. @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
  12. public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
  13. return new OrderedHiddenHttpMethodFilter();
  14. }

//自定义filter @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter(){ HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); methodFilter.setMethodParam(“_m”); return methodFilter; }

  1. Rest原理(表单提交要使用REST的时候)
  2. - 表单提交会带上**_method=PUT**
  3. - **请求过来被**HiddenHttpMethodFilter拦截
  4. - 请求是否正常,并且是POST
  5. - 获取到**_method**的值。
  6. - 兼容以下请求;**PUT**.**DELETE**.**PATCH**
  7. - **原生requestpost),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。**
  8. - **过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。**
  9. **Rest使用客户端工具,**
  10. - PostMan直接发送Putdelete等方式请求,无需Filter
  11. ```yaml
  12. spring:
  13. mvc:
  14. hiddenmethod:
  15. filter:
  16. enabled: true #开启页面表单的Rest功能

2、请求映射原理

Springboot2之Web开发场景模块 - 图9
SpringMVC功能分析都从 org.springframework.web.servlet.DispatcherServlet-》doDispatch()

  1. protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. HttpServletRequest processedRequest = request;
  3. HandlerExecutionChain mappedHandler = null;
  4. boolean multipartRequestParsed = false;
  5. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
  6. try {
  7. ModelAndView mv = null;
  8. Exception dispatchException = null;
  9. try {
  10. processedRequest = checkMultipart(request);
  11. multipartRequestParsed = (processedRequest != request);
  12. // 找到当前请求使用哪个Handler(Controller的方法)处理
  13. mappedHandler = getHandler(processedRequest);
  14. //HandlerMapping:处理器映射。/xxx->>xxxx

Springboot2之Web开发场景模块 - 图10
RequestMappingHandlerMapping:保存了所有@RequestMapping 和handler的映射规则。
Springboot2之Web开发场景模块 - 图11
所有的请求映射都在HandlerMapping中。

  • SpringBoot自动配置欢迎页的 WelcomePageHandlerMapping 。访问 /能访问到index.html;
  • SpringBoot自动配置了默认 的 RequestMappingHandlerMapping
  • 请求进来,挨个尝试所有的HandlerMapping看是否有请求信息。
    • 如果有就找到这个请求对应的handler
    • 如果没有就是下一个 HandlerMapping
  • 我们需要一些自定义的映射处理,我们也可以自己给容器中放HandlerMapping。自定义 HandlerMapping
    1. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    2. if (this.handlerMappings != null) {
    3. for (HandlerMapping mapping : this.handlerMappings) {
    4. HandlerExecutionChain handler = mapping.getHandler(request);
    5. if (handler != null) {
    6. return handler;
    7. }
    8. }
    9. }
    10. return null;
    11. }

    1、普通参数与基本注解

    1.1、注解:

    @PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody ```java @RestController public class ParameterTestController {
  1. // car/2/owner/zhangsan
  2. @GetMapping("/car/{id}/owner/{username}")
  3. public Map<String,Object> getCar(@PathVariable("id") Integer id,
  4. @PathVariable("username") String name,
  5. @PathVariable Map<String,String> pv,
  6. @RequestHeader("User-Agent") String userAgent,
  7. @RequestHeader Map<String,String> header,
  8. @RequestParam("age") Integer age,
  9. @RequestParam("inters") List<String> inters,
  10. @RequestParam Map<String,String> params,
  11. @CookieValue("_ga") String _ga,
  12. @CookieValue("_ga") Cookie cookie){
  13. Map<String,Object> map = new HashMap<>();

// map.put(“id”,id); // map.put(“name”,name); // map.put(“pv”,pv); // map.put(“userAgent”,userAgent); // map.put(“headers”,header); map.put(“age”,age); map.put(“inters”,inters); map.put(“params”,params); map.put(“_ga”,_ga); System.out.println(cookie.getName()+”===>”+cookie.getValue()); return map; }

  1. @PostMapping("/save")
  2. public Map postMethod(@RequestBody String content){
  3. Map<String,Object> map = new HashMap<>();
  4. map.put("content",content);
  5. return map;
  6. }
  7. //1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
  8. //2、SpringBoot默认是禁用了矩阵变量的功能
  9. // 手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
  10. // removeSemicolonContent(移除分号内容)支持矩阵变量的
  11. //3、矩阵变量必须有url路径变量才能被解析
  12. @GetMapping("/cars/{path}")
  13. public Map carsSell(@MatrixVariable("low") Integer low,
  14. @MatrixVariable("brand") List<String> brand,
  15. @PathVariable("path") String path){
  16. Map<String,Object> map = new HashMap<>();
  17. map.put("low",low);
  18. map.put("brand",brand);
  19. map.put("path",path);
  20. return map;
  21. }
  22. // /boss/1;age=20/2;age=10
  23. @GetMapping("/boss/{bossId}/{empId}")
  24. public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
  25. @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
  26. Map<String,Object> map = new HashMap<>();
  27. map.put("bossAge",bossAge);
  28. map.put("empAge",empAge);
  29. return map;
  30. }

}

  1. <a name="LU2AG"></a>
  2. ### 1.2、Servlet API:
  3. WebRequest、ServletRequest、MultipartRequest、 HttpSession、javax.servlet.http.PushBuilder、Principal、InputStream、Reader、HttpMethod、Locale、TimeZone、ZoneId<br />**ServletRequestMethodArgumentResolver 以上的部分参数**
  4. ```java
  5. @Override
  6. public boolean supportsParameter(MethodParameter parameter) {
  7. Class<?> paramType = parameter.getParameterType();
  8. return (WebRequest.class.isAssignableFrom(paramType) ||
  9. ServletRequest.class.isAssignableFrom(paramType) ||
  10. MultipartRequest.class.isAssignableFrom(paramType) ||
  11. HttpSession.class.isAssignableFrom(paramType) ||
  12. (pushBuilder != null && pushBuilder.isAssignableFrom(paramType)) ||
  13. Principal.class.isAssignableFrom(paramType) ||
  14. InputStream.class.isAssignableFrom(paramType) ||
  15. Reader.class.isAssignableFrom(paramType) ||
  16. HttpMethod.class == paramType ||
  17. Locale.class == paramType ||
  18. TimeZone.class == paramType ||
  19. ZoneId.class == paramType);
  20. }

1.3、复杂参数:

MapModel(map、model里面的数据会被放在request的请求域 request.setAttribute)、Errors/BindingResult、RedirectAttributes( 重定向携带数据)ServletResponse(response)、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder

  1. Map<String,Object> map, Model model, HttpServletRequest request 都是可以给request域中放数据,
  2. request.getAttribute();

Map、Model类型的参数,会返回 mavContainer.getModel();—-> BindingAwareModelMap 是Model 也是Map
mavContainer.getModel(); 获取到值的
Springboot2之Web开发场景模块 - 图12

Springboot2之Web开发场景模块 - 图13

Springboot2之Web开发场景模块 - 图14

1.4、自定义对象参数:

可以自动类型转换与格式化,可以级联封装。

  1. /**
  2. * 姓名: <input name="userName"/> <br/>
  3. * 年龄: <input name="age"/> <br/>
  4. * 生日: <input name="birth"/> <br/>
  5. * 宠物姓名:<input name="pet.name"/><br/>
  6. * 宠物年龄:<input name="pet.age"/>
  7. */
  8. @Data
  9. public class Person {
  10. private String userName;
  11. private Integer age;
  12. private Date birth;
  13. private Pet pet;
  14. }
  15. @Data
  16. public class Pet {
  17. private String name;
  18. private String age;
  19. }
  20. result

2、POJO封装过程

  • ServletModelAttributeMethodProcessor

    3、参数处理原理

  • HandlerMapping中找到能处理请求的Handler(Controller.method())

  • 为当前Handler 找一个适配器 HandlerAdapter; RequestMappingHandlerAdapter
  • 适配器执行目标方法并确定方法参数的每一个值

    1、HandlerAdapter

    Springboot2之Web开发场景模块 - 图15
    0 - 支持方法上标注@RequestMapping
    1 - 支持函数式编程的
    xxxxxx

    2、执行目标方法

    1. // Actually invoke the handler.
    2. //DispatcherServlet -- doDispatch
    3. mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    ```java mav = invokeHandlerMethod(request, response, handlerMethod); //执行目标方法

//ServletInvocableHandlerMethod Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs); //获取方法的参数值 Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);

  1. <a name="MrIwI"></a>
  2. ### 3、参数解析器-HandlerMethodArgumentResolver
  3. 确定将要执行的目标方法的每一个参数的值是什么;<br />SpringMVC目标方法能写多少种参数类型。取决于参数解析器。<br />![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1603263283504-85bbd4d5-a9af-4dbf-b6a2-30b409868774.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_20%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&from=url&id=X7zDD&margin=%5Bobject%20Object%5D&originHeight=849&originWidth=691&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)<br />![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1603263394724-33122714-9d06-42ec-bf45-e440e8b49c05.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_23%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&from=url&id=Jhnie&margin=%5Bobject%20Object%5D&originHeight=124&originWidth=821&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  4. - 当前解析器是否支持解析这种参数
  5. - 支持就调用 resolveArgument
  6. <a name="bL9KZ"></a>
  7. ### 4、返回值处理器
  8. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1603263524227-386da4be-43b1-4b17-a2cc-8cf886346af9.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_22%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&from=url&id=tN0eU&margin=%5Bobject%20Object%5D&originHeight=599&originWidth=771&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  9. <a name="swVCE"></a>
  10. ### 5、如何确定目标方法每一个参数的值
  11. ```java
  12. ============InvocableHandlerMethod==========================
  13. protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
  14. Object... providedArgs) throws Exception {
  15. MethodParameter[] parameters = getMethodParameters();
  16. if (ObjectUtils.isEmpty(parameters)) {
  17. return EMPTY_ARGS;
  18. }
  19. Object[] args = new Object[parameters.length];
  20. for (int i = 0; i < parameters.length; i++) {
  21. MethodParameter parameter = parameters[i];
  22. parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
  23. args[i] = findProvidedArgument(parameter, providedArgs);
  24. if (args[i] != null) {
  25. continue;
  26. }
  27. if (!this.resolvers.supportsParameter(parameter)) {
  28. throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver"));
  29. }
  30. try {
  31. args[i] = this.resolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);
  32. }
  33. catch (Exception ex) {
  34. // Leave stack trace for later, exception may actually be resolved and handled...
  35. if (logger.isDebugEnabled()) {
  36. String exMsg = ex.getMessage();
  37. if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) {
  38. logger.debug(formatArgumentError(parameter, exMsg));
  39. }
  40. }
  41. throw ex;
  42. }
  43. }
  44. return args;
  45. }

5.1、挨个判断所有参数解析器那个支持解析这个参数

  1. @Nullable
  2. private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
  3. HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
  4. if (result == null) {
  5. for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) {
  6. if (resolver.supportsParameter(parameter)) {
  7. result = resolver;
  8. this.argumentResolverCache.put(parameter, result);
  9. break;
  10. }
  11. }
  12. }
  13. return result;
  14. }

5.2、解析这个参数的值

  1. 调用各自 HandlerMethodArgumentResolver resolveArgument 方法即可

5.3、自定义类型参数 封装POJO

ServletModelAttributeMethodProcessor 这个参数处理器支持
是否为简单类型。

  1. public static boolean isSimpleValueType(Class<?> type) {
  2. return (Void.class != type && void.class != type &&
  3. (ClassUtils.isPrimitiveOrWrapper(type) ||
  4. Enum.class.isAssignableFrom(type) ||
  5. CharSequence.class.isAssignableFrom(type) ||
  6. Number.class.isAssignableFrom(type) ||
  7. Date.class.isAssignableFrom(type) ||
  8. Temporal.class.isAssignableFrom(type) ||
  9. URI.class == type ||
  10. URL.class == type ||
  11. Locale.class == type ||
  12. Class.class == type));
  13. }
  1. @Override
  2. @Nullable
  3. public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
  4. NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
  5. Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
  6. Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");
  7. String name = ModelFactory.getNameForParameter(parameter);
  8. ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
  9. if (ann != null) {
  10. mavContainer.setBinding(name, ann.binding());
  11. }
  12. Object attribute = null;
  13. BindingResult bindingResult = null;
  14. if (mavContainer.containsAttribute(name)) {
  15. attribute = mavContainer.getModel().get(name);
  16. }
  17. else {
  18. // Create attribute instance
  19. try {
  20. attribute = createAttribute(name, parameter, binderFactory, webRequest);
  21. }
  22. catch (BindException ex) {
  23. if (isBindExceptionRequired(parameter)) {
  24. // No BindingResult parameter -> fail with BindException
  25. throw ex;
  26. }
  27. // Otherwise, expose null/empty value and associated BindingResult
  28. if (parameter.getParameterType() == Optional.class) {
  29. attribute = Optional.empty();
  30. }
  31. bindingResult = ex.getBindingResult();
  32. }
  33. }
  34. if (bindingResult == null) {
  35. // Bean property binding and validation;
  36. // skipped in case of binding failure on construction.
  37. WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
  38. if (binder.getTarget() != null) {
  39. if (!mavContainer.isBindingDisabled(name)) {
  40. bindRequestParameters(binder, webRequest);
  41. }
  42. validateIfApplicable(binder, parameter);
  43. if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
  44. throw new BindException(binder.getBindingResult());
  45. }
  46. }
  47. // Value type adaptation, also covering java.util.Optional
  48. if (!parameter.getParameterType().isInstance(attribute)) {
  49. attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
  50. }
  51. bindingResult = binder.getBindingResult();
  52. }
  53. // Add resolved attribute and BindingResult at the end of the model
  54. Map<String, Object> bindingResultModel = bindingResult.getModel();
  55. mavContainer.removeAttributes(bindingResultModel);
  56. mavContainer.addAllAttributes(bindingResultModel);
  57. return attribute;
  58. }

WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
WebDataBinder :web数据绑定器,将请求参数的值绑定到指定的JavaBean里面
WebDataBinder 利用它里面的 Converters 将请求数据转成指定的数据类型。再次封装到JavaBean中
GenericConversionService:在设置每一个值的时候,找它里面的所有converter那个可以将这个数据类型(request带来参数的字符串)转换到指定的类型(JavaBean — Integer)
byte — > file
@FunctionalInterfacepublic interface Converter

Springboot2之Web开发场景模块 - 图16

Springboot2之Web开发场景模块 - 图17

未来我们可以给WebDataBinder里面放自己的Converter;
private static final class StringToNumber implements Converter

  1. //1、WebMvcConfigurer定制化SpringMVC的功能
  2. @Bean
  3. public WebMvcConfigurer webMvcConfigurer(){
  4. return new WebMvcConfigurer() {
  5. @Override
  6. public void configurePathMatch(PathMatchConfigurer configurer) {
  7. UrlPathHelper urlPathHelper = new UrlPathHelper();
  8. // 不移除;后面的内容。矩阵变量功能就可以生效
  9. urlPathHelper.setRemoveSemicolonContent(false);
  10. configurer.setUrlPathHelper(urlPathHelper);
  11. }
  12. @Override
  13. public void addFormatters(FormatterRegistry registry) {
  14. registry.addConverter(new Converter<String, Pet>() {
  15. @Override
  16. public Pet convert(String source) {
  17. // 啊猫,3
  18. if(!StringUtils.isEmpty(source)){
  19. Pet pet = new Pet();
  20. String[] split = source.split(",");
  21. pet.setName(split[0]);
  22. pet.setAge(Integer.parseInt(split[1]));
  23. return pet;
  24. }
  25. return null;
  26. }
  27. });
  28. }
  29. };
  30. }

6、目标方法执行完成

将所有的数据都放在 ModelAndViewContainer;包含要去的页面地址View。还包含Model数据。
Springboot2之Web开发场景模块 - 图18

7、处理派发结果

processDispatchResult(processedRequest, response,
mappedHandler, mv, dispatchException);

renderMergedOutputModel(mergedModel,
getRequestToExpose(request), response);

  1. InternalResourceView
  2. @Override
  3. protected void renderMergedOutputModel(
  4. Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
  5. // Expose the model object as request attributes.
  6. exposeModelAsRequestAttributes(model, request);
  7. // Expose helpers as request attributes, if any.
  8. exposeHelpers(request);
  9. // Determine the path for the request dispatcher.
  10. String dispatcherPath = prepareForRendering(request, response);
  11. // Obtain a RequestDispatcher for the target resource (typically a JSP).
  12. RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
  13. if (rd == null) {
  14. throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
  15. "]: Check that the corresponding file exists within your web application archive!");
  16. }
  17. // If already included or response already committed, perform include, else forward.
  18. if (useInclude(request, response)) {
  19. response.setContentType(getContentType());
  20. if (logger.isDebugEnabled()) {
  21. logger.debug("Including [" + getUrl() + "]");
  22. }
  23. rd.include(request, response);
  24. }
  25. else {
  26. // Note: The forwarded resource is supposed to determine the content type itself.
  27. if (logger.isDebugEnabled()) {
  28. logger.debug("Forwarding to [" + getUrl() + "]");
  29. }
  30. rd.forward(request, response);
  31. }
  32. }
  1. 暴露模型作为请求域属性
  2. // Expose the model object as request attributes.
  3. exposeModelAsRequestAttributes(model, request);
  1. protected void exposeModelAsRequestAttributes(Map<String, Object> model,
  2. HttpServletRequest request) throws Exception {
  3. //model中的所有数据遍历挨个放在请求域中
  4. model.forEach((name, value) -> {
  5. if (value != null) {
  6. request.setAttribute(name, value);
  7. }
  8. else {
  9. request.removeAttribute(name);
  10. }
  11. });
  12. }

4、数据响应与内容协商

image.png

1、响应JSON

1.1、jackson.jar+@ResponseBody

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. web场景自动引入了json场景
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-json</artifactId>
  9. <version>2.3.4.RELEASE</version>
  10. <scope>compile</scope>
  11. </dependency>

Springboot2之Web开发场景模块 - 图20

给前端自动返回json数据;

1、返回值解析器

Springboot2之Web开发场景模块 - 图21

  1. try {
  2. this.returnValueHandlers.handleReturnValue(
  3. returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
  4. }
  1. @Override
  2. public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
  3. ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
  4. HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType);
  5. if (handler == null) {
  6. throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName());
  7. }
  8. handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
  9. }
  1. RequestResponseBodyMethodProcessor
  2. @Override
  3. public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
  4. ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
  5. throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
  6. mavContainer.setRequestHandled(true);
  7. ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
  8. ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
  9. // Try even with null return value. ResponseBodyAdvice could get involved.
  10. // 使用消息转换器进行写出操作
  11. writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
  12. }

2、返回值解析器原理

Springboot2之Web开发场景模块 - 图22

  • 1、返回值处理器判断是否支持这种类型返回值 supportsReturnType
  • 2、返回值处理器调用 handleReturnValue 进行处理
  • 3、RequestResponseBodyMethodProcessor 可以处理返回值标了@ResponseBody 注解的。
      1. 利用 MessageConverters 进行处理 将数据写为json
        • 1、内容协商(浏览器默认会以请求头的方式告诉服务器他能接受什么样的内容类型)
        • 2、服务器最终根据自己自身的能力,决定服务器能生产出什么样内容类型的数据,
        • 3、SpringMVC会挨个遍历所有容器底层的 HttpMessageConverter ,看谁能处理?
          • 1、得到MappingJackson2HttpMessageConverter可以将对象写为json
          • 2、利用MappingJackson2HttpMessageConverter将对象转为json再写出去。

Springboot2之Web开发场景模块 - 图23

1.2、SpringMVC到底支持哪些返回值

  1. ModelAndView
  2. Model
  3. View
  4. ResponseEntity
  5. ResponseBodyEmitter
  6. StreamingResponseBody
  7. HttpEntity
  8. HttpHeaders
  9. Callable
  10. DeferredResult
  11. ListenableFuture
  12. CompletionStage
  13. WebAsyncTask
  14. @ModelAttribute 且为对象类型的
  15. @ResponseBody 注解 ---> RequestResponseBodyMethodProcessor

1.3、HTTPMessageConverter原理

1、MessageConverter规范

Springboot2之Web开发场景模块 - 图24
HttpMessageConverter: 看是否支持将 此 Class类型的对象,转为MediaType类型的数据。
例子:Person对象转为JSON。或者 JSON转为Person

2、默认的MessageConverter

Springboot2之Web开发场景模块 - 图25
0 - 只支持Byte类型的
1 - String
2 - String
3 - Resource
4 - ResourceRegion
5 - DOMSource.class \ SAXSource.class) \ StAXSource.class \StreamSource.class \Source.class
6 - MultiValueMap
7 - true
8 - true
9 - 支持注解方式xml处理的。

最终 MappingJackson2HttpMessageConverter 把对象转为JSON(利用底层的jackson的objectMapper转换的)
Springboot2之Web开发场景模块 - 图26

2、内容协商

根据客户端接收能力不同,返回不同媒体类型的数据。

1、引入xml依赖

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.dataformat</groupId>
  3. <artifactId>jackson-dataformat-xml</artifactId>
  4. </dependency>

2、postman分别测试返回json和xml

只需要改变请求头中Accept字段。Http协议中规定的,告诉服务器本客户端可以接收的数据类型。
Springboot2之Web开发场景模块 - 图27

3、开启浏览器参数方式内容协商功能

为了方便内容协商,开启基于请求参数的内容协商功能。
spring: contentnegotiation: favor-parameter: true #开启请求参数内容协商模式
发请求: http://localhost:8080/test/person?format=json
http://localhost:8080/test/person?format=xml

Springboot2之Web开发场景模块 - 图28
确定客户端接收什么样的内容类型;
1、Parameter策略优先确定是要返回json数据(获取请求头中的format的值)
Springboot2之Web开发场景模块 - 图29
2、最终进行内容协商返回给客户端json即可。

4、内容协商原理

  • 1、判断当前响应头中是否已经有确定的媒体类型。MediaType
  • 2、获取客户端(PostMan、浏览器)支持接收的内容类型。(获取客户端Accept请求头字段)【application/xml】
    • contentNegotiationManager 内容协商管理器 默认使用基于请求头的策略
    • Springboot2之Web开发场景模块 - 图30
    • HeaderContentNegotiationStrategy 确定客户端可以接收的内容类型
    • Springboot2之Web开发场景模块 - 图31
  • 3、遍历循环所有当前系统的 MessageConverter,看谁支持操作这个对象(Person)
  • 4、找到支持操作Person的converter,把converter支持的媒体类型统计出来。
  • 5、客户端需要【application/xml】。服务端能力【10种、json、xml】
  • Springboot2之Web开发场景模块 - 图32
  • 6、进行内容协商的最佳匹配媒体类型
  • 7、用 支持 将对象转为 最佳匹配媒体类型 的converter。调用它进行转化 。

Springboot2之Web开发场景模块 - 图33
导入了jackson处理xml的包,xml的converter就会自动进来

  1. WebMvcConfigurationSupport
  2. jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
  3. if (jackson2XmlPresent) {
  4. Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
  5. if (this.applicationContext != null) {
  6. builder.applicationContext(this.applicationContext);
  7. }
  8. messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
  9. }

5、自定义 MessageConverter

实现多协议数据兼容。json、xml、x-guigu
0、@ResponseBody 响应数据出去 调用 RequestResponseBodyMethodProcessor 处理
1、Processor 处理方法返回值。通过 MessageConverter 处理
2、所有 MessageConverter 合起来可以支持各种媒体类型数据的操作(读、写)
3、内容协商找到最终的 messageConverter

SpringMVC的什么功能。一个入口给容器中添加一个 WebMvcConfigurer

  1. @Bean
  2. public WebMvcConfigurer webMvcConfigurer(){
  3. return new WebMvcConfigurer() {
  4. @Override
  5. public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
  6. }
  7. }
  8. }

Springboot2之Web开发场景模块 - 图34

Springboot2之Web开发场景模块 - 图35

有可能我们添加的自定义的功能会覆盖默认很多功能,导致一些默认的功能失效。
大家考虑,上述功能除了我们完全自定义外?SpringBoot有没有为我们提供基于配置文件的快速修改媒体类型功能?怎么配置呢?【提示:参照SpringBoot官方文档web开发内容协商章节】

5、视图解析与模板引擎

视图解析:SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

1、视图解析

image.png

1、视图解析原理流程

1、目标方法处理的过程中,所有数据都会被放在 ModelAndViewContainer 里面。包括数据和视图地址
2、方法的参数是一个自定义类型对象(从请求参数中确定的),把他重新放在 ModelAndViewContainer
3、任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。
4、processDispatchResult 处理派发结果(页面改如何响应)

  • 1、render(mv, request, response); 进行页面渲染逻辑
    • 1、根据方法的String返回值得到 View 对象【定义了页面的渲染逻辑】
      • 1、所有的视图解析器尝试是否能根据当前返回值得到View对象
      • 2、得到了 redirect:/main.html —> Thymeleaf new RedirectView()
      • 3、ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。
      • 4、view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作
        • RedirectView 如何渲染【重定向到一个页面】
        • 1、获取目标url地址
        • 2、response.sendRedirect(encodedURL);

视图解析:

  • 返回值以 forward: 开始: new InternalResourceView(forwardUrl); —> 转发request.getRequestDispatcher(path).forward(request, response);
  • 返回值以 redirect: 开始: new RedirectView() —》 render就是重定向
  • 返回值是普通字符串: new ThymeleafView()—->

自定义视图解析器+自定义视图; 大厂学院。

Springboot2之Web开发场景模块 - 图37
Springboot2之Web开发场景模块 - 图38

Springboot2之Web开发场景模块 - 图39

Springboot2之Web开发场景模块 - 图40

2、模板引擎-Thymeleaf

1、thymeleaf简介

Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
现代化、服务端Java模板引擎

2、基本语法

1、表达式

表达式名字 语法 用途
变量取值 ${…} 获取请求域、session域、对象等值
选择变量 *{…} 获取上下文对象值
消息 #{…} 获取国际化等值
链接 @{…} 生成链接
片段表达式 ~{…} jsp:include 作用,引入公共页面片段

2、字面量

文本值: ‘one text’ , ‘Another one!’ ,…数字: 0 , 34 , 3.0 , 12.3 ,…布尔值: true , false
空值: null
变量: one,two,…. 变量不能有空格

3、文本操作

字符串拼接: +
变量替换: |The name is ${name}|

4、数学运算

运算符: + , - , * , / , %

5、布尔运算

运算符: and , or
一元运算: ! , not

6、比较运算

比较: > , < , >= , <= ( gt , lt , ge , le )等式: == , != ( eq , ne )

7、条件运算

If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

8、特殊操作

无操作: _

3、设置属性值-th:attr

设置单个值

  1. <form action="subscribe.html" th:attr="action=@{/subscribe}">
  2. <fieldset>
  3. <input type="text" name="email" />
  4. <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  5. </fieldset>
  6. </form>

设置多个值

  1. <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

以上两个的代替写法 th:xxxx

  1. <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
  2. <form action="subscribe.html" th:action="@{/subscribe}">

所有h5兼容的标签写法
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

4、迭代

  1. <tr th:each="prod : ${prods}">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>
  1. <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>

5、条件运算

  1. <a href="comments.html"
  2. th:href="@{/product/comments(prodId=${prod.id})}"
  3. th:if="${not #lists.isEmpty(prod.comments)}">view</a>
  1. <div th:switch="${user.role}">
  2. <p th:case="'admin'">User is an administrator</p>
  3. <p th:case="#{roles.manager}">User is a manager</p>
  4. <p th:case="*">User is some other thing</p>
  5. </div>

6、属性优先级

Springboot2之Web开发场景模块 - 图41

3、thymeleaf使用

1、引入Starter

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

2、自动配置好了thymeleaf

  1. @Configuration(proxyBeanMethods = false)
  2. @EnableConfigurationProperties(ThymeleafProperties.class)
  3. @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
  4. @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
  5. public class ThymeleafAutoConfiguration { }

自动配好的策略

  • 1、所有thymeleaf的配置值都在 ThymeleafProperties
  • 2、配置好了 SpringTemplateEngine
  • 3、配好了 ThymeleafViewResolver
  • 4、我们只需要直接开发页面

    1. public static final String DEFAULT_PREFIX = "classpath:/templates/";
    2. public static final String DEFAULT_SUFFIX = ".html"; //xxx.html

    3、页面开发

    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 th:text="${msg}">哈哈</h1>
    9. <h2>
    10. <a href="www.atguigu.com" th:href="${link}">去百度</a> <br/>
    11. <a href="www.atguigu.com" th:href="@{link}">去百度2</a>
    12. </h2>
    13. </body>
    14. </html>

    4、构建后台管理系统

    1、项目创建

    thymeleaf、web-starter、devtools、lombok

2、静态资源处理

自动配置好,我们只需要把所有静态资源放到 static 文件夹下

3、路径构建

th:action=”@{/login}”

4、模板抽取

th:insert/replace/include

5、页面跳转

  1. @PostMapping("/login")
  2. public String main(User user, HttpSession session, Model model){
  3. if(StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())){
  4. //把登陆成功的用户保存起来
  5. session.setAttribute("loginUser",user);
  6. //登录成功重定向到main.html; 重定向防止表单重复提交
  7. return "redirect:/main.html";
  8. }else {
  9. model.addAttribute("msg","账号密码错误");
  10. //回到登录页面
  11. return "login";
  12. }
  13. }

6、数据渲染

  1. @GetMapping("/dynamic_table")
  2. public String dynamic_table(Model model){
  3. //表格内容的遍历
  4. List<User> users = Arrays.asList(new User("zhangsan", "123456"),
  5. new User("lisi", "123444"),
  6. new User("haha", "aaaaa"),
  7. new User("hehe ", "aaddd"));
  8. model.addAttribute("users",users);
  9. return "table/dynamic_table";
  10. }
  1. <table class="display table table-bordered" id="hidden-table-info">
  2. <thead>
  3. <tr>
  4. <th>#</th>
  5. <th>用户名</th>
  6. <th>密码</th>
  7. </tr>
  8. </thead>
  9. <tbody>
  10. <tr class="gradeX" th:each="user,stats:${users}">
  11. <td th:text="${stats.count}">Trident</td>
  12. <td th:text="${user.userName}">Internet</td>
  13. <td >[[${user.password}]]</td>
  14. </tr>
  15. </tbody>
  16. </table>

6、拦截器

1、HandlerInterceptor 接口

  1. /**
  2. * 登录检查
  3. * 1、配置好拦截器要拦截哪些请求
  4. * 2、把这些配置放在容器中
  5. */
  6. @Slf4j
  7. public class LoginInterceptor implements HandlerInterceptor {
  8. /**
  9. * 目标方法执行之前
  10. * @param request
  11. * @param response
  12. * @param handler
  13. * @return
  14. * @throws Exception
  15. */
  16. @Override
  17. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  18. String requestURI = request.getRequestURI();
  19. log.info("preHandle拦截的请求路径是{}",requestURI);
  20. //登录检查逻辑
  21. HttpSession session = request.getSession();
  22. Object loginUser = session.getAttribute("loginUser");
  23. if(loginUser != null){
  24. //放行
  25. return true;
  26. }
  27. //拦截住。未登录。跳转到登录页
  28. request.setAttribute("msg","请先登录");
  29. // re.sendRedirect("/");
  30. request.getRequestDispatcher("/").forward(request,response);
  31. return false;
  32. }
  33. /**
  34. * 目标方法执行完成以后
  35. * @param request
  36. * @param response
  37. * @param handler
  38. * @param modelAndView
  39. * @throws Exception
  40. */
  41. @Override
  42. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  43. log.info("postHandle执行{}",modelAndView);
  44. }
  45. /**
  46. * 页面渲染以后
  47. * @param request
  48. * @param response
  49. * @param handler
  50. * @param ex
  51. * @throws Exception
  52. */
  53. @Override
  54. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  55. log.info("afterCompletion执行异常{}",ex);
  56. }
  57. }

2、配置拦截器

  1. /**
  2. * 1、编写一个拦截器实现HandlerInterceptor接口
  3. * 2、拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
  4. * 3、指定拦截规则【如果是拦截所有,静态资源也会被拦截】
  5. */
  6. @Configuration
  7. public class AdminWebConfig implements WebMvcConfigurer {
  8. @Override
  9. public void addInterceptors(InterceptorRegistry registry) {
  10. registry.addInterceptor(new LoginInterceptor())
  11. .addPathPatterns("/**") //所有请求都被拦截包括静态资源
  12. .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求
  13. }
  14. }

3、拦截器原理

1、根据当前请求,找到HandlerExecutionChain【可以处理请求的handler以及handler的所有 拦截器】
2、先来顺序执行 所有拦截器的 preHandle方法

  • 1、如果当前拦截器prehandler返回为true。则执行下一个拦截器的preHandle
  • 2、如果当前拦截器返回为false。直接 倒序执行所有已经执行了的拦截器的 afterCompletion;

3、如果任何一个拦截器返回false。直接跳出不执行目标方法
4、所有拦截器都返回True。执行目标方法
5、倒序执行所有拦截器的postHandle方法。
6、前面的步骤有任何异常都会直接倒序触发 afterCompletion
7、页面成功渲染完成以后,也会倒序触发 afterCompletion

Springboot2之Web开发场景模块 - 图42

Springboot2之Web开发场景模块 - 图43

7、文件上传

1、页面表单

  1. <form method="post" action="/upload" enctype="multipart/form-data">
  2. <input type="file" name="file"><br>
  3. <input type="submit" value="提交">
  4. </form>

2、文件上传代码

  1. /**
  2. * MultipartFile 自动封装上传过来的文件
  3. * @param email
  4. * @param username
  5. * @param headerImg
  6. * @param photos
  7. * @return
  8. */
  9. @PostMapping("/upload")
  10. public String upload(@RequestParam("email") String email,
  11. @RequestParam("username") String username,
  12. @RequestPart("headerImg") MultipartFile headerImg,
  13. @RequestPart("photos") MultipartFile[] photos) throws IOException {
  14. log.info("上传的信息:email={},username={},headerImg={},photos={}",
  15. email,username,headerImg.getSize(),photos.length);
  16. if(!headerImg.isEmpty()){
  17. //保存到文件服务器,OSS服务器
  18. String originalFilename = headerImg.getOriginalFilename();
  19. headerImg.transferTo(new File("H:\\cache\\"+originalFilename));
  20. }
  21. if(photos.length > 0){
  22. for (MultipartFile photo : photos) {
  23. if(!photo.isEmpty()){
  24. String originalFilename = photo.getOriginalFilename();
  25. photo.transferTo(new File("H:\\cache\\"+originalFilename));
  26. }
  27. }
  28. }
  29. return "main";
  30. }

3、自动配置原理

文件上传自动配置类-MultipartAutoConfiguration-MultipartProperties

  • 自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
  • 原理步骤
    • 1、请求进来使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回MultipartHttpServletRequest)文件上传请求
    • 2、参数解析器来解析请求中的文件内容封装成MultipartFile
    • 3、将request中文件信息封装为一个Map;MultiValueMap

FileCopyUtils。实现文件流的拷贝

  1. @PostMapping("/upload")
  2. public String upload(@RequestParam("email") String email,
  3. @RequestParam("username") String username,
  4. @RequestPart("headerImg") MultipartFile headerImg,
  5. @RequestPart("photos") MultipartFile[] photos)

Springboot2之Web开发场景模块 - 图44

8、异常处理

1、错误处理

1、默认规则

  • 默认情况下,Spring Boot提供/error处理所有错误的映射
  • 对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
  • Springboot2之Web开发场景模块 - 图45Springboot2之Web开发场景模块 - 图46
  • **要对其进行自定义,添加View解析为error
  • 要完全替换默认行为,可以实现 ErrorController 并注册该类型的Bean定义,或添加ErrorAttributes类型的组件以使用现有机制但替换其内容。
  • error/下的4xx,5xx页面会被自动解析;

    • Springboot2之Web开发场景模块 - 图47

      2、定制错误处理逻辑

  • 自定义错误页

    • error/404.html error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html;如果都没有就触发白页
  • @ControllerAdvice+@ExceptionHandler处理全局异常;底层是 ExceptionHandlerExceptionResolver 支持的
  • @ResponseStatus+自定义异常 ;底层是 ResponseStatusExceptionResolver ,把responsestatus注解的信息底层调用 response.sendError(statusCode, resolvedReason);tomcat发送的/error
  • Spring底层的异常,如 参数类型转换异常;DefaultHandlerExceptionResolver 处理框架底层的异常。
    • response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    • Springboot2之Web开发场景模块 - 图48
  • 自定义实现 HandlerExceptionResolver 处理异常;可以作为默认的全局异常处理规则
    • Springboot2之Web开发场景模块 - 图49
  • ErrorViewResolver实现自定义处理异常;
    • response.sendError 。error请求就会转给controller
    • 你的异常没有任何人能处理。tomcat底层 response.sendError。error请求就会转给controller
    • basicErrorController 要去的页面地址是 ErrorViewResolver

3、异常处理自动配置原理

  • ErrorMvcAutoConfiguration 自动配置异常处理规则
    • 容器中的组件:类型:DefaultErrorAttributes -> id:errorAttributes
      • public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver
      • DefaultErrorAttributes:定义错误页面中可以包含哪些数据。
      • Springboot2之Web开发场景模块 - 图50
      • Springboot2之Web开发场景模块 - 图51
    • 容器中的组件:类型:BasicErrorController —> id:basicErrorController(json+白页 适配响应)
      • 处理默认 /error 路径的请求;页面响应 new ModelAndView(“error”, model);
      • 容器中有组件 View->id是error;(响应默认错误页)
      • 容器中放组件 BeanNameViewResolver(视图解析器);按照返回的视图名作为组件的id去容器中找View对象。
    • 容器中的组件:类型:DefaultErrorViewResolver -> id:conventionErrorViewResolver
      • 如果发生错误,会以HTTP的状态码 作为视图页地址(viewName),找到真正的页面
      • error/404、5xx.html

如果想要返回页面;就会找error视图【StaticView】。(默认是一个白页)

Springboot2之Web开发场景模块 - 图52写出去json
Springboot2之Web开发场景模块 - 图53 错误页

4、异常处理步骤流程

1、执行目标方法,目标方法运行期间有任何异常都会被catch、而且标志当前请求结束;并且用 dispatchException
2、进入视图解析流程(页面渲染?)
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
3、mv = processHandlerException;处理handler发生的异常,处理完成返回ModelAndView;

  • 1、遍历所有的 handlerExceptionResolvers,看谁能处理当前异常【HandlerExceptionResolver处理器异常解析器】
  • Springboot2之Web开发场景模块 - 图54
  • 2、系统默认的 异常解析器;
  • Springboot2之Web开发场景模块 - 图55
    • 1、DefaultErrorAttributes先来处理异常。把异常信息保存到rrequest域,并且返回null;
    • 2、默认没有任何人能处理异常,所以异常会被抛出
      • 1、如果没有任何人能处理最终底层就会发送 /error 请求。会被底层的BasicErrorController处理
      • 2、解析错误视图;遍历所有的 ErrorViewResolver 看谁能解析。
      • Springboot2之Web开发场景模块 - 图56
      • 3、默认的 DefaultErrorViewResolver ,作用是把响应状态码作为错误页的地址,error/500.html
      • 4、模板引擎最终响应这个页面 error/500.html

        9、Web原生组件注入(Servlet、Filter、Listener)

        1、使用Servlet API

        @ServletComponentScan(basePackages = “com.atguigu.admin”) :指定原生Servlet组件都放在那里
        @WebServlet(urlPatterns = “/my”):效果:直接响应,没有经过Spring的拦截器?
        @WebFilter(urlPatterns={“/css/*”,“/images/*”})
        @WebListener
        推荐可以这种方式;

扩展:DispatchServlet 如何注册进来

  • 容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。
  • 通过 ServletRegistrationBean 把 DispatcherServlet 配置进来。
  • 默认映射的是 / 路径。

Springboot2之Web开发场景模块 - 图57
Tomcat-Servlet;
多个Servlet都能处理到同一层路径,精确优选原则
A: /my/
B: /my/1

2、使用RegistrationBean

  1. @Configuration
  2. public class MyRegistConfig {
  3. @Bean
  4. public ServletRegistrationBean myServlet(){
  5. MyServlet myServlet = new MyServlet();
  6. return new ServletRegistrationBean(myServlet,"/my","/my02");
  7. }
  8. @Bean
  9. public FilterRegistrationBean myFilter(){
  10. MyFilter myFilter = new MyFilter();
  11. // return new FilterRegistrationBean(myFilter,myServlet());
  12. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
  13. filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
  14. return filterRegistrationBean;
  15. }
  16. @Bean
  17. public ServletListenerRegistrationBean myListener(){
  18. MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
  19. return new ServletListenerRegistrationBean(mySwervletContextListener);
  20. }
  21. }

10、嵌入式Servlet容器

1、切换嵌入式Servlet容器

  • 默认支持的webServer
    • Tomcat, Jetty, or Undertow
    • ServletWebServerApplicationContext 容器启动寻找ServletWebServerFactory 并引导创建服务器
  • 切换服务器

Springboot2之Web开发场景模块 - 图58

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-tomcat</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  • 原理
    • SpringBoot应用启动发现当前是Web应用。web场景包-导入tomcat
    • web应用会创建一个web版的ioc容器 ServletWebServerApplicationContext
    • ServletWebServerApplicationContext 启动的时候寻找 ServletWebServerFactory(Servlet 的web服务器工厂—-> Servlet 的web服务器)
    • SpringBoot底层默认有很多的WebServer工厂;TomcatServletWebServerFactory, JettyServletWebServerFactory, or UndertowServletWebServerFactory
    • 底层直接会有一个自动配置类。ServletWebServerFactoryAutoConfiguration
    • ServletWebServerFactoryAutoConfiguration导入了ServletWebServerFactoryConfiguration(配置类)
    • ServletWebServerFactoryConfiguration 配置类 根据动态判断系统中到底导入了那个Web服务器的包。(默认是web-starter导入tomcat包),容器中就有 TomcatServletWebServerFactory
    • TomcatServletWebServerFactory 创建出Tomcat服务器并启动;TomcatWebServer 的构造器拥有初始化方法initialize—-this.tomcat.start();
    • 内嵌服务器,就是手动把启动服务器的代码调用(tomcat核心jar包存在)

2、定制Servlet容器

  • 实现 WebServerFactoryCustomizer
    • 把配置文件的值和ServletWebServerFactory 进行绑定
  • 修改配置文件 server.xxx
  • 直接自定义 ConfigurableServletWebServerFactory

xxxxxCustomizer:定制化器,可以改变xxxx的默认规则

  1. import org.springframework.boot.web.server.WebServerFactoryCustomizer;
  2. import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  6. @Override
  7. public void customize(ConfigurableServletWebServerFactory server) {
  8. server.setPort(9000);
  9. }
  10. }

11、定制化原理

1、定制化的常见方式

  • 修改配置文件;
  • xxxxxCustomizer;
  • 编写自定义的配置类 xxxConfiguration;+ @Bean替换、增加容器中默认组件;视图解析器
  • Web应用 编写一个配置类实现 WebMvcConfigurer 即可定制化web功能;+ @Bean给容器中再扩展一些组件

    1. @Configuration
    2. public class AdminWebConfig implements WebMvcConfigurer
  • @EnableWebMvc + WebMvcConfigurer —— @Bean可以全面接管SpringMVC,所有规则全部自己重新配置; 实现定制和扩展功能

    • 原理
    • 1、WebMvcAutoConfiguration 默认的SpringMVC的自动配置功能类。静态资源、欢迎页…..
    • 2、一旦使用 @EnableWebMvc 、。会 @Import(DelegatingWebMvcConfiguration.class)
    • 3、DelegatingWebMvcConfiguration 的 作用,只保证SpringMVC最基本的使用
      • 把所有系统中的 WebMvcConfigurer 拿过来。所有功能的定制都是这些 WebMvcConfigurer 合起来一起生效
      • 自动配置了一些非常底层的组件。RequestMappingHandlerMapping、这些组件依赖的组件都是从容器中获取
      • public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
    • 4、WebMvcAutoConfiguration 里面的配置要能生效 必须 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    • 5、@EnableWebMvc 导致了 WebMvcAutoConfiguration 没有生效。
  • … …

    2、原理分析套路

    场景starter - xxxxAutoConfiguration - 导入xxx组件 - 绑定xxxProperties — 绑定配置文件项