主要操作 controller下面添加两个类
JacksonConfig
代码如下
package com.sansec.sanatom.controller;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
//直接屏蔽掉值为null的参数
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
}
GlobalExceptionHandler
package com.sansec.sanatom.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.sansec.sanatom.utils.response.ExceptionResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
*
- @author lvxingsheng
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final SimpleDateFormat dateFormat=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
@ExceptionHandler(Exception.class)
ResponseEntity<?> handleException(Exception e){
ExceptionResponse response = new ExceptionResponse();
response.setStatus(“1”);
response.setAppId("");
response.setPreId("");
response.setMessage(“Exception msg=”+e.getMessage());
response.setTime(dateFormat.format(new Date()));
return new ResponseEntity(response,HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value=MethodArgumentNotValidException.class)
ResponseEntity<?> MethodArgumentNotValidHandler(MethodArgumentNotValidException e)
{
ExceptionResponse response = new ExceptionResponse();
StringBuilder builder = new StringBuilder();
for (FieldError error : e.getBindingResult().getFieldErrors()) {
builder.append(“errMsg=”);
builder.append(error.getDefaultMessage());
builder.append(",");
builder.append(error.getObjectName());
builder.append("=");
builder.append(error.getRejectedValue());
builder.append(";");
}
response.setStatus(“1”);
response.setTime(dateFormat.format(new Date()));
response.setMessage(builder.toString());
return new ResponseEntity(response,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
来源:CSDN
作者:晕死的小猫
链接:https://blog.csdn.net/qq_33058833/article/details/104519456