SpringBoot常用类

时间:2019-10-23
本文章向大家介绍SpringBoot常用类,主要包括SpringBoot常用类使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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);
    }
}

原文地址:https://www.cnblogs.com/thetop/p/11727248.html