spring boot 官方文档翻译28 Developing Web Application

28 Developing Web Application

Spring Boot非常适合开发web应用程序,你可以使用内嵌的Tomcat,Jetty或Undertow、netty轻轻松松地创建一个HTTP服务器。大多数的web应用都可以使用spring-boot-starter-web模块进行快速搭建和运行。你也可以使用spring-boot-starter-webflux创建一个reactive web应用。

28.1 The “Spring Web MVC Framework”

Spring Web MVC框架(通常简称为 Spring MVC)是一个rich 'model view controller’web 框架,允许用户创建特定的@Controller或者@RestController beans 处理传入的http请求。通过@RequestMapping注解可以将控制器中的方法映射到相应的HTTP请求。

下面是一个@RestController( serves JSON data)例子:

@RestController
@RequestMapping(value="/users")
public class MyRestController {
   
	@RequestMapping(value="/{user}", method=RequestMethod.GET)
	public User getUser(@PathVariable Long user) {
   
		// ...
	}
	@RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
	List<Customer> getUserCustomers(@PathVariable Long user) {
   
		// ...
	}
	@RequestMapping(value="/{user}", method=RequestMethod.DELETE)
	public User deleteUser(@PathVariable Long user) {
   
		// ...
	}
}

Spring MVC 自动配置

Spring Boot 为Spring MVC提供了自动配置,这些配置适用于大部分应用。

自动配置在Spring的默认配置之上添加了以下特性:

  • 注册了ContentNegotiatingViewResolver和BeanNameViewResolver beans
  • 支持静态资源访问,其中包括对WebJars的支持
  • 主动注册了Converter、Converter和Converter beans
  • 静态index.html 首页的支持。
  • 支持自定义favicon.ico
  • ConfigurableWebBindingInitializer 的自动使用

如果想保持Spring Boot MVC特性,增加额外的MVC配置(比如(interceptors, formatters, view controllers, and other features),可以通过添加自己的 WebMvcConfigurer 并使用@Configuration注解,但是不要使@EnableWebMvc

如果想提供自定义的 RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or
ExceptionHandlerExceptionResolver实例,可以声明一个WebMvcRegistrationsAdapter 实例。

如果想完全控制Spring MVC,则在自己的WebMvcConfigurer上使用@Configuration + @EnableWebMVC注解 。

HttpMessageConverters

Spring MVC 使用HttpMessageConverters 接口转换HTTP请求和响应。合适的默认配置可以开箱即用。例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用UTF-8编码。

可以使用Spring Boot的HttpMessageConverters类添加或自定义 Converters:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
@Configuration
public class MyConfiguration {
   
	@Bean
	public HttpMessageConverters customConverters() {
   
		HttpMessageConverter<?> additional = ..
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值