安县建设局网站,网站建设分金手指排名一,便宜的广州网站建设服务,网页设计与网页制作的实验报告一、概述
1.1SpringBoot整合SpringMVC配置 SpringBoot对SpringMVC的配置主要包括以下几个方面#xff1a; 自动配置#xff1a;SpringBoot会自动配置一个嵌入式的Servlet容器#xff08;如Tomcat#xff09;#xff0c;并为我们提供默认的SpringMVC配置。这样我们无需手动…一、概述
1.1SpringBoot整合SpringMVC配置 SpringBoot对SpringMVC的配置主要包括以下几个方面 自动配置SpringBoot会自动配置一个嵌入式的Servlet容器如Tomcat并为我们提供默认的SpringMVC配置。这样我们无需手动配置Servlet容器和SpringMVC只需添加相应的依赖即可快速搭建一个Web应用。 视图解析器SpringBoot默认使用Thymeleaf作为视图解析器如果需要更换其他视图解析器可以在pom.xml中修改对应的依赖。静态资源处理SpringBoot默认会处理静态资源如HTML、CSS、JavaScript等并将其放在项目的/static或/public目录下。如果需要自定义静态资源的处理方式可以通过编写一个类实现WebMvcConfigurer接口并重写addResourceHandlers方法来实现。拦截器SpringBoot支持自定义拦截器可以通过实现HandlerInterceptor接口来创建拦截器并在主配置类上添加EnableWebMvc注解然后在该注解的configurers属性中添加自定义的拦截器。 异常处理SpringBoot默认使用WhitelabelErrorView来处理异常如果需要自定义异常处理方式可以通过编写一个类实现ErrorController接口并重写errorHtml方法来实现。参数绑定SpringBoot支持多种参数绑定方式如RequestParam、PathVariable、RequestBody等。如果需要自定义参数绑定方式可以通过编写一个类实现MethodArgumentResolver接口并重写resolveArgument方法来实现。 跨域支持SpringBoot默认支持CORS跨域请求如果需要自定义跨域配置可以通过编写一个类实现WebMvcConfigurer接口并重写addCorsMappings方法来实现。 总之SpringBoot为我们提供了丰富的默认配置和灵活的扩展机制可以方便地定制和扩展SpringMVC以满足项目需求。 1.2WebMvcConfiguration概述 WebMvcConfigurer接口是Spring提供的一个用于自定义Spring MVC配置的接口主要提供了WebMvcConfigurer接口是Spring提供的一个用于自定义Spring MVC配置的接口主要提供了多个回调方法包括添加或修改Spring MVC的配置如添加拦截器自定义消息转换器等。具体来说WebMvcConfigurer接口的主要方法包括 - configurePathMatchS此方法用于配置路由请求规则。- configureContentNegotiationS该方法用于内容协商配置。- configureAsyncSupportS该方法用于异步支持配置。- configureDefaultServletHandlingS该方法用于配置默认静态资源处理器。- addFormattersS此方法用于注册自定义转化器。- addInterceptorsS此方法用于拦截器配置。- addResourceHandlersS此方法用于资源处理。- addCorsMappingsS此方法用于CORS配置。 在使用时只需要实现WebMvcConfigurer接口重写上述的方法即可完成自定义配置。 二、详解
2.1资源处理器
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.concurrent.TimeUnit;
Configuration
public class MyConfig implements WebMvcConfigurer {Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {// 保留以前的配置WebMvcConfigurer.super.addResourceHandlers(registry);// 自定义配置registry.addResourceHandler(/static/**).addResourceLocations(classpath:/a/, classpath:/b/).setCacheControl(CacheControl.maxAge(1180, TimeUnit.SECONDS));}
}实现了WebMvcConfigurer接口。它的作用是配置静态资源的处理方式。具体来说它会将/static/**路径下的资源映射到classpath:/a/和classpath:/b/这两个目录下并设置缓存时间为1180秒。 2.2 路径匹配 Spring5.3之后加入了更多的请求路径匹配的实现策略 以前只支持AntPathMatcher策略现在提供了PathPatternParser策略。并且可以让我们指定到底使用那种策略。 Ant风格 Ant风格的路径模式语法具有以下规则 *:表示任意数量的字符。?:表示任意一个字符。**:表示任意数量的目录。{}:表示一个命名的模式占位符。[]:表示字符集合例如[a-z]表示小写字母。 PathPatternParser策略 PathPatternParser是Spring框架中用于解析URL路径模式的策略类。它可以解析和匹配URL路径模式并且支持Ant风格的通配符例如?、*和**。 ·PathPatternParser在jmh基准测试下有6~8倍吞l提升降低30%~40%空间分配率·PathPatternParser兼容AntPathMatcheri语法并支持更多类型的路径模式·PathPatternParser*多段匹配的支持仅允许在模式末尾使用 /*** 默认使用新版 PathPatternParser 进行路径匹配* 不能匹配 ** 在中间的情况剩下的和 antPathMatcher语法兼容* param request* param path* return*/GetMapping(/a*/b?/**/{p1:[a-f]}/**)public String hello(HttpServletRequest request, PathVariable(p1) String path) {log.info(路径变量p1 {}, path);String uri request.getRequestURI();return uri;} 模式转换
# 使用新版的路径匹配策略PathPatternParser
spring.mvc.pathmatch.matching-strategypath_pattern_parser# 使用老版的路径匹配策略AntPathMatcher
# spring.mvc.pathmatch.matching-strategyant_path_matcher2.3内容协商配置 在Spring Boot中内容协商Content Negotiation是一种处理不同客户端请求的方法。它允许服务器根据请求的内容类型、参数或其他条件来选择合适的响应格式。要配置内容协商你需要使用WebMvcConfigurer接口的实现类。 基于请求头内容协商默认 客户端向服务端发送请求携带HTTP标准的Accept请求头。 .Accept:application/json.text/xml.text/yaml服务端根据客户端情求头期望的数据类型进行动态返回 基于请求参数内容协商需要开启 发送请求GET/projects/spring-boot?formatjson匹配到GetMapping(*/projects/spring-boot)根据参数协商优先返回json类型数据【需要开启参数匹配设置】发送请求GET/projects/spring-boot?format:xml,优先返回xml类型数据 web场景自动引入了json场景
在 spring-boot-starter-web 依赖下
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-json/artifactIdversion2.3.4.RELEASE/versionscopecompile/scope
/dependency内容协助实现转xml 请求同一个接口可以返回json和xml不同格式数据 引入支持写出xml内容依赖 dependencygroupIdcom.fasterxml.jackson.dataformat/groupIdartifactIdjackson-dataformat-xml/artifactId
/dependency 标注注解 package com.yanyu.springplustest4.dto;import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;JacksonXmlRootElement // 可以写出为xml文档
Data
AllArgsConstructor
NoArgsConstructor
public class Person {private Long id;private String userName;private String email;private Integer age;private String role;
}JacksonXmlRootElement注解是Jackson库中的一个注解用于指定XML文档的根元素。当使用Jackson库将Java对象转换为XML时可以使用此注解来设置根元素的标签名。例如 import com.fasterxml.jackson.annotation.JacksonXmlRootElement;JacksonXmlRootElement(localName student)
public class Student {private String name;private int age;// 省略getter和setter方法
} 在这个例子中Student类被标记为JacksonXmlRootElement(localName student)表示生成的XML文档的根元素标签名为student。 开启基于请求参数的内容协商 # 开启基于请求参数的内容协商功能。 默认参数名format。 默认此功能不开启
spring.mvc.contentnegotiation.favor-parametertrue
# 指定内容协商时使用的参数名。默认是 format
spring.mvc.contentnegotiation.parameter-nametype 测试 package com.yanyu.springplustest4.Controller;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanyu.springplustest4.dto.Person;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.*;import java.util.Locale;/*** author lfy* Description* create 2023-04-10 18:31*/
Slf4j
RestController
public class HelloController {/*** 1、默认支持把对象写为json。因为默认web场景导入了jackson处理json的包;jackson-core* 2、jackson也支持把数据写为xml。导入xml相关依赖* return*/GetMapping(/person)public Person person(){Person person new Person();person.setId(1L);person.setUserName(张三);person.setEmail(aaaqq.com);person.setAge(18);return person;}} 配置协商规则与支持类型
修改内容协商方式 #使用参数进行内容协商
spring.mvc.contentnegotiation.favor-parametertrue
#自定义参数名默认为format
spring.mvc.contentnegotiation.parameter-namemyparam 大多数 MediaType 都是开箱即用的。也可以自定义内容类型 spring.mvc.contentnegotiation.media-types.yamltext/yaml
2.4消息转化器
WebMvcAutoConfiguration提供几种默认HttpMessageConverters
EnableWebMvcConfiguration通过 addDefaultHttpMessageConverters添加了默认的MessageConverter如下 ByteArrayHttpMessageConverter 支持字节数据读写StringHttpMessageConverter 支持字符串读写ResourceHttpMessageConverter支持资源读写ResourceRegionHttpMessageConverter: 支持分区资源写出AllEncompassingFormHttpMessageConverter支持表单xml/json读写MappingJackson2HttpMessageConverter 支持请求响应体Json读写 默认8个 系统提供默认的MessageConverter 功能有限仅用于json或者普通返回数据。额外增加新的内容协商功能必须增加新的HttpMessageConverter
在Spring Boot中可以通过配置类来自定义消息转换器。例如以下代码演示了如何配置一个将Java对象转换为JSON格式的消息的转换器
Configuration
public class WebConfig implements WebMvcConfigurer {Overridepublic void configureMessageConverters(ListHttpMessageConverter? converters) {converters.add(new MappingJackson2HttpMessageConverter());}
} 举例
1. 增加yaml返回支持
导入依赖
dependencygroupIdcom.fasterxml.jackson.dataformat/groupIdartifactIdjackson-dataformat-yaml/artifactId
/dependency
把对象写出成YAML
package com.yanyu.springplustest4.Controller;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanyu.springplustest4.dto.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import java.util.Locale;Slf4j
RestController
public class HelloController {GetMapping(/person)public Person person(/*RequestBody Person person*/){Person person new Person();person.setId(1L);person.setUserName(张三);person.setEmail(aaaqq.com);person.setAge(18);return person;}public static void aaa(String[] args) throws JsonProcessingException {Person person new Person();person.setId(1L);person.setUserName(张三);person.setEmail(aaaqq.com);person.setAge(18);YAMLFactory factory new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);ObjectMapper mapper new ObjectMapper(factory);String s mapper.writeValueAsString(person);System.out.println(s);}
}
编写配置
#新增一种媒体类型
spring.mvc.contentnegotiation.media-types.yamltext/yaml
增加HttpMessageConverter组件专门负责把对象写出为yaml格式
package com.yanyu.springplustest4;import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;/*** 自定义的HTTP消息转换器用于将对象转换为YAML格式*/
public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverterObject {private ObjectMapper objectMapper null; // 用于将对象转换为YAML格式的ObjectMapper/*** 构造方法配置YAML格式的ObjectMapper*/public MyYamlHttpMessageConverter(){super(new MediaType(text, yaml, Charset.forName(UTF-8)));// 告诉SpringBoot这个MessageConverter支持哪种媒体类型YAMLFactory factory new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
// 禁用YAML文档起始标记this.objectMapper new ObjectMapper(factory);}/*** 判断是否支持转换指定的类* param clazz 要转换的类* return 如果是对象类型非基本类型返回true否则返回false*/Overrideprotected boolean supports(Class? clazz) {return true;}/*** 从HTTP输入消息中读取数据暂不实现* param clazz 要转换的类* param inputMessage HTTP输入消息* return 返回null* throws IOException 如果发生I/O错误* throws HttpMessageNotReadableException 如果无法读取消息*/Overrideprotected Object readInternal(Class? clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {return null;}/*** 将对象写入HTTP输出消息中* param methodReturnValue 要写出的对象* param outputMessage HTTP输出消息* throws IOException 如果发生I/O错误* throws HttpMessageNotWritableException 如果无法写出消息*/Overrideprotected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {// 使用try-with-resources语法自动关闭流try(OutputStream os outputMessage.getBody()){this.objectMapper.writeValue(os, methodReturnValue);}}
}2.5国际化配置
国际化的自动配置参照MessageSourceAutoConfiguration
实现步骤
Spring Boot 在类路径根下查找messages资源绑定文件。文件名为messages.properties多语言可以定义多个消息文件命名为messages_区域代码.properties。如 messages.properties默认messages_zh_CN.properties中文环境messages_en_US.properties英语环境在程序中可以自动注入 MessageSource组件获取国际化的配置项值在页面中可以使用表达式 #{}获取国际化的配置项值 Autowired //国际化取消息用的组件MessageSource messageSource;GetMapping(/haha)public String haha(HttpServletRequest request){Locale locale request.getLocale();//利用代码的方式获取国际化配置文件中指定的配置项的值String login messageSource.getMessage(login, null, locale);return login;}配置 spring.messages.basenamemessages
spring.messages.encodingUTF-81. spring.messages.basenamemessages这个属性设置了Spring Boot默认的消息文件的基本名称即在类路径下查找名为messages的文件。这些文件通常用于存储国际化消息例如错误消息、提示消息等。 2. spring.messages.encodingUTF-8这个属性设置了Spring Boot默认的消息文件的字符编码。在这个例子中编码被设置为UTF-8这意味着消息文件中的文本将使用UTF-8编码进行存储和读取。