小總結(jié) SpringBoot是一個基于Spring的工具集,去幫我們完成了大量的配置。在SpringBoot中有一個約定大于配置的概念,就是他把我們很多第三方框架幫我們寫好了,而且把我們整個第三方框架所需要的依賴全都通過起步依賴加進去了。開發(fā)中只需要加入起步依賴就可以實現(xiàn)某個場景的開發(fā),比如web開發(fā)場景、mybatis開發(fā)場景、Redis開發(fā)場景....
SpringBoot web相關(guān)配置
1 靜態(tài)資源訪問
Springboot工程的靜態(tài)資源約定(默認)要求放在如下目錄
resource
? —/static
? — /public
? —/resources
? —/META-INF/resources
優(yōu)先級順序 /META-INF/resources >>> resources >>> static >>> public
1.1 配置自定義靜態(tài)資源路徑
基于配置類的方式
@Configuration // 表示當(dāng)前類是一個配置類
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imag/**")//瀏覽器資源訪問路徑
.addResourceLocations("classpath:/images/"); //映射本地資源路徑
}
}
基于配置文件的方式
spring:
mvc:
static-path-pattern: /images/**
resources:
static-locations: classpath:/images/
2 統(tǒng)一異常處理
SpringBoot提供了一個默認的映射:/error,當(dāng)處理中拋出異常之后,會轉(zhuǎn)到請求中處理,并且該請求有一個全局的錯誤頁面用來展示異常內(nèi)容。
2.1 自定義全局處理異常
走視圖解析器的配置
- advice 底層是AOP技術(shù) 報錯之后,在不修改Controller層的基礎(chǔ)之上做增強
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String exceptionHandle(HttpServletRequest request, Exception e){
return "errorPage";
}
@ExceptionHandler(NullPointerException.class)
public String exceptionHandle1(HttpServletRequest request, Exception e){
//可根據(jù)不同的異常做出不同的處理
return "errorPage1";
}
}
前后端分離的配置(返回json數(shù)據(jù))
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResultData exceptionHandle(HttpServletRequest request, Exception e){
return new ResultData(101,"出錯啦??!");
}
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public ResultData exceptionHandle1(HttpServletRequest request, Exception e){
//可根據(jù)不同的異常做出不同的處理
return new ResultData(101,"出錯啦111?。?);
}
}
3 文件上傳
后端Controller
注意:如果這個方法不加@ResponseBody 那么就會走視圖解析器,會404
@Controller
public class UploadController {
@RequestMapping("upload")
//注意:如果這個方法不加@ResponseBody 那么就會走視圖解析器,會404
@ResponseBody
public ResultData upload(@RequestParam("file") MultipartFile file) throws IOException {
try {
String originalFilename = file.getOriginalFilename();
String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = UUID.randomUUID().toString().replace("-","")+ext;
file.transferTo(new File("D:\\workspace\\upload\\"+filename));
} catch (Exception e) {
e.printStackTrace();
return new ResultData(100,"上傳失敗");
}
return new ResultData(0,"上傳成功");
}
}
文件上傳配置(非必須配置)
spring:
servlet:
multipart:
# 單個上傳文件大?。J1MB)
max-file-size: 2MB
# 總上傳文件大?。J10MB)
max-request-size: 20MB
使用postman測試
springboot內(nèi)置tomcat中配置外部訪問路徑
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
//添加虛擬路徑,相同于通過一個路徑來訪問本地磁盤上的內(nèi)容
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:D:\\workspace\\upload\\");
}
}
4 攔截器
定義攔截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser == null){
//登錄失敗跳轉(zhuǎn)到登錄頁面
response.sendRedirect(request.getContextPath()+"/login.html");
return false;
}
return true;//登錄成功放行
}
}
配置攔截器文章來源:http://www.zghlxwxcb.cn/news/detail-429651.html
- 添加攔截器
- 定義攔截器的路徑
- 定義排除攔截的路徑
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()) //添加攔截器
.addPathPatterns("/**") //定義攔截的路徑
.excludePathPatterns("/images"); //定義排除攔截的路徑
}
}
5 統(tǒng)一跨域請求處理
統(tǒng)一的跨域處理文章來源地址http://www.zghlxwxcb.cn/news/detail-429651.html
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders("*")
.allowCredentials(true)
.allowedMethods("*");
}
}
@Configuration //表示當(dāng)前類是一個配置類
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**")
.addResourceLocations("classpath:/images/");
registry.addResourceHandler("/tupian/**")
.addResourceLocations("file:D:\\workspace\\upload\\");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //請求的資源 /**表示所有資源 、
.allowedOrigins("*") //允許指定的源能訪問
// .allowedOriginPatterns("*")//允許的請求地址 一般不需要
.allowedHeaders("*") //允許攜帶的請求頭
.allowedMethods("*"); //允許的請求方式
//.allowCredentials(true) //允許是否攜帶cookie
//注意:當(dāng)設(shè)置允許攜帶Cookie不允許將指定源設(shè)置為所有
}
}
到了這里,關(guān)于SpringBoot -05 SpringBoot web相關(guān)配置(靜態(tài)資源訪問、統(tǒng)一異常處理、文件上傳、攔截器、統(tǒng)一跨域請求處理)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!