SpringBoot学习笔记10-Web-Servlet Web应用

本文详细介绍了SpringBoot中Spring Web MVC的自动配置,包括HttpMessageConverters、静态内容处理、错误处理和跨源资源共享(CORS)。Spring MVC使用HttpMessageConverter进行HTTP请求和响应的转换,支持自定义JSON序列化和反序列化。默认情况下,Spring Boot为静态内容提供服务,可以自定义静态资源路径。错误处理通过/error映射进行,并支持自定义错误页面。此外,文章还讨论了CORS配置和跨域资源共享的处理方式。
摘要由CSDN通过智能技术生成

以spring官方文档为基础,官方地址:Spring Boot_Web

Spring Boot非常适合web应用程序的开发。可以使用嵌入的Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。大多数web应用程序使用spring-boot-starter-web模块来快速启动和运行。也可以选择使用spring-boot-starter-webflux模块来构建响应式web应用程序。

如果想构建基于servlet的web应用程序,可以利用Spring Boot对Spring MVC或Jersey的自动配置。

1. Spring Web MVC框架

Spring Web MVC框架(通常称为“Spring MVC”)是一个丰富的“模型-视图-控制器”Web框架。Spring MVC允许使用@Controller或@RestController bean来处理传入的HTTP请求, controller控制器中的方法通过@RequestMapping注释映射到HTTP。

下面是一个典型的@RestController服务示例:

import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class MyRestController {
   

    private final UserRepository userRepository;

    private final CustomerRepository customerRepository;

    public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) {
   
        this.userRepository = userRepository;
        this.customerRepository = customerRepository;
    }

    @GetMapping("/{user}")
    public User getUser(@PathVariable Long userId) {
   
        return this.userRepository.findById(userId).get();
    }

    @GetMapping("/{user}/customers")
    public List<Customer> getUserCustomers(@PathVariable Long userId) {
   
        return this.userRepository.findById(userId).map(this.customerRepository::findByUser).get();
    }

    @DeleteMapping("/{user}")
    public void deleteUser(@PathVariable Long userId) {
   
        this.userRepository.deleteById(userId);
    }
}

Spring MVC是核心Spring框架的一部分,Spring参考文档中提供了详细的信息。

1.1 Spring MVC 的自动配置

Spring Boot为大多数应用提供了Spring MVC的自动配置。它的自动配置在Spring的默认值之上添加了以下特性:

  • 包含了ContentNegotiatingViewResolver和BeanNameViewResolver bean。
  • 对服务静态资源的支持,包括对webjar的支持。
  • Converter、GenericConverter和Formatter bean的自动注册。
  • 对HttpMessageConverters的支持。
  • MessageCodesResolver的自动注册。
  • 静态index.html的支持。
  • 自动使用ConfigurableWebBindingInitializer bean。

如果想保留那些Spring Boot的MVC定制,并做更多的MVC定制(拦截器、格式化器、视图控制器和其他特性),可以添加自己的WebMvcConfigurer类型的@Configuration类,但不要添加@EnableWebMvc。

如果想提供自定义的实例RequestMappingHandlerMapping,RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver,并且依旧保留Spring Boot MVC的定制,可以声明一个WebMvcRegistrations,利用它来提供这些组件的自定义实例。

如果想完全控制Spring MVC,可以添加被@EnableWebMvc注释过的@Configuration配置,或者也可以添加被DelegatingWebMvcConfiguration注释过的@Configuration配置,具体可参见@EnableWebMvc的Javadoc中所述。

1.2 HttpMessageConverters

Spring MVC使用HttpMessageConverter接口来转换HTTP请求和响应。对象可以自动转换为JSON(通过使用Jackson库)或XML(如果Jackson XML扩展可用,则使用Jackson XML扩展;如果Jackson XML扩展不可用,则使用JAXB)。默认情况下,字符串采用UTF-8编码。Jackson库)是默认解析json的库。

如果需要添加或自定义转换器,可以使用Spring Boot的HttpMessageConverters类,如下所示:

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

@Configuration(proxyBeanMethods = false)
public class MyHttpMessageConvertersConfiguration {
   

    @Bean
    public HttpMessageConverters customConverters() {
   
        HttpMessageConverter<?> additional = new AdditionalHttpMessageConverter();
        HttpMessageConverter<?> another = new AnotherHttpMessageConverter();
        return new HttpMessageConverters(additional, another);
    }
}

上述自定义的HttpMessageConverter bean都将被添加到转换器列表中(这是添加配置类来注入Bean)。也可以用同样的方法重写默认转换器(启动类继承extends WebMvcConfigurerAdapter,然后覆盖方法configureMessageConverters)

1.3 自定义JSON序列化器和反序列化器

在使用Jackson来序列化/反序列化JSON数据时,可能需要编写自己的JsonSerializer和JsonDeserializer类。自定义序列化器通常通过一个模块注册到Jackson,但是Spring Boot其实提供了一个@JsonComponent注释,它使得直接注册Spring bean变得更简单。

可以直接在JsonSerializer、JsonDeserializer或KeyDeserializer实现上使用@JsonComponent注释。也可以在包含序列化器/反序列化器作为内部类的类上使用它,如下面的例子所示:

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值