:) spring mvc 是前提
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-
这个start依赖的其他库
配置信息
- 关于bean的配置在 WebMvcAutoConfiguration 这个类里面,这个类配置了很多bean,类似InternalResourceViewResolver, BeanNameViewResolver
- 添加一些其他的配置信息,使用WebMvcConfigurer(这个接口提供了很多add方法)。
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
System.out.println("===> "+handler.toString());
return true;
}
});
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { }
@Override
public void addFormatters(FormatterRegistry registry) { }
}
HTTP请求格式化(request json > entity / response entity > json)
- spring boot 自动配置了很多格式化请求参数的bean
- 自定义主要是注册一个HttpMessageConverters的bean,这个bean里面包含了多个HttpMessageConverter实例
@Configuration
public class MvcConfig {
@Bean
public HttpMessageConverters converters() {
return new HttpMessageConverters(new UserConverter());
}
}
静态资源处理
-
默认的静态资源路径映射到classpath的static目录,途中的index.html对应的路径是http://localhost:8080/index.html
修改默认的映射路径,注册一个实现了WebMvcConfigurer接口的组件,并重写addResourceHandlers方法
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/*.html")
.addResourceLocations("classpath:/static/");
}
}
错误处理
- @ControllerAdvice 这个注解只能捕获controller的异常信息
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
- 如果请求还没有到达controller就异常了,这个时候就只有用其他办法了,spring boot会经错误信息映射到 /error 这个路径 , 这个会更具produces属性来返回不同的数据格式
@RestController
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {
private static final String PATH = "/error";
@Autowired
ErrorAttributes attributes;
@RequestMapping(value = PATH,produces = {MediaType.APPLICATION_JSON_VALUE})
public String eror(HttpServletRequest request, HttpServletResponse response){
return "error";
}
@Override
public String getErrorPath() {
return PATH;
}
}
End