SpringBoot常用类
1 设置全局异常处理
/**
* 设置全局异常处理
*/
@ResponseBody
@ControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler(value = Exception.class)
public String errorHandle(Exception e){
e.printStackTrace();
return ResultResponse.getJsonResult(-1, e.getMessage());
}
}
2 设置跨域问题
@Configuration
public class MyConfiguration {
/**
* 设置跨域问题
* @return
*/
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
};
}
}
3 规范返回结果
/**
* 规范返回结果,简化返回过程的工具类
*/
public class ResultResponse {
/**
* 当获取上传的数据发生错误时的返回值
*/
public static final String CHECKDATAERRORRESULT = "{\"code\":-1,\"data\":[],\"message\":\"请求参数错误!\"}";
public static final String UPDATADATAERRORRESULT = "{\"code\":-1,\"data\":[],\"message\":\"数据库操作失败!\"}";
/**
* 通用的返回格式化json数据
* @param code
* @param params
* @return
*/
public static String getJsonResult(int code, Object...params){
Map map = new HashMap();
map.put("code", code);
String message = (params.length >= 1 && params[0] instanceof String) ? (String)params[0] : "";
map.put("mssage", message);
Object data = (params.length >= 2) ? params[1] : new ArrayList();
map.put("data", data);
Gson gson = new Gson();
return gson.toJson(map);
}
}