1. 加解密工具
上面的三个包在资料里面找
2. 通用json返回类
public class JsonResponse<T> {
private String code;
private String msg;
private T data;
public JsonResponse(String code, String msg){
this.code = code;
this.msg = msg;
}
public JsonResponse(T data){
this.data = data;
msg = "成功";
code = "0";
}
public static JsonResponse<String> success(){
return new JsonResponse<>(null);
}
public static JsonResponse<String> success(String data){
return new JsonResponse<>(data);
}
public static JsonResponse<String> fail(){
return new JsonResponse<>("1", "失败");
}
public static JsonResponse<String> fail(String code, String msg){
return new JsonResponse<>(code, msg);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
写在dao包下的com.imooc.bilibili.domain
3. JSON信息转换配置
引入依赖
写在service下的config包下
@Configuration
public class JsonHttpMessageConverterConfig {
@Bean
@Primary
public HttpMessageConverters fastJsonHttpMessageConverters(){
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.MapSortField,
SerializerFeature.DisableCircularReferenceDetect
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//如果使用feign进行微服务间的接口调用,则需要加上该配置
fastConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
return new HttpMessageConverters(fastConverter);
}
}
4. 全局异常处理配置
写在dao服务下的exception包下
public class ConditionException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String code;
public ConditionException(String code, String name){
super(name);
this.code = code;
}
public ConditionException(String name){
super(name);
code = "500";
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
写在service下的handler包下
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CommonGlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonResponse<String> commonExceptionHandler(HttpServletRequest request, Exception e){
String errorMsg = e.getMessage();
if(e instanceof ConditionException){
String errorCode = ((ConditionException)e).getCode();
return new JsonResponse<>(errorCode, errorMsg);
}else{
return new JsonResponse<>("500",errorMsg);
}
}
}