Spring Boot适合来开发WEB应用程序,因为它提供了很多便利,如支持嵌入式HTTP服务器;提供了starter来管理依赖,快速开始,例如使用spring-boot-starter-web开始web应用程序开发,使用spring-boot-starter-webflux开始响应式web开发。
在SpringMVC框架中,使用@Controller或@RestController标注请求处理器,使用@RequestMapping标志请求处理方法,例如:
@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 Boot的自动配置特性在开发Spring MVC WEB应用时相当方便。
默认情况下,Spring Boot自动配置提供的东东:
如果上面的东东并不能满足你,你还可以:
HttpMessageConverters用来转换响应消息,例如把请求处理方法返回的对象直接转换成JSON或XML。
如果你需要自定义转换器,可以这样做:
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
@Configuration(proxyBeanMethods = false)
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}
}
如果你使用Jackson来序列化和反序列JSON数据,你可能希望自定义JsonSerializer和JsonDeserializer,Spring Boot提供了一个@JsonComponent注解可以使自定义更加简单。
@JsonComponent可以直接使用在JsonSerializer、JsonDeserializer和KeyDeserializer实现类上,也可以使用在外部类上,例如:
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;
@JsonComponent
public class Example {
public static class Serializer extends JsonSerializer<SomeObject> {
// ...
}
public static class Deserializer extends JsonDeserializer<SomeObject> {
// ...
}
}
MessageCodesResover用于为绑定错误生成错误码。
默认情况下,静态资源放在/static、/public、/resources目录下,Spring MVC使用ResoucesHttpRequestHandler来处理静态资源,你可以重写WebMvcConfigurer的addResourceHandlers来自定义ResoucesHttpRequestHandler。
默认情况下,静态资源映射到/**,你可以通过spring.mvc.static-path-pattern属性重写,示例:
spring.mvc.static-path-pattern=/resources/**
同样可以通过spring.resources.static-locations自定义静态资源的位置,示例:
spring.resources.static-locations=/icon/
默认的欢迎页是index.html,如果index.html不存在,则查找index模板文件
favicon.icon文件直接放在静态资源目录下。
原文:https://www.cnblogs.com/stronger-brother/p/12120781.html