SpringBoot 2.0 은 Rest 스타일 데이터 구조 와 통일 이상 처 리 를 통일 적 으로 되 돌려 줍 니 다.
38902 단어 springboot
package com.futao.springmvcdemo.model.system;
import org.joda.time.DateTime;
import java.sql.Timestamp;
/**
* @author futao
* Created on 2018/9/22-21:47.
* Rest
*/
public class RestResult {
/**
*
*/
private boolean success;
/**
* code
*/
private String code;
/**
* ,
*/
private Object data;
/**
* ,
*/
private Object errorMessage;
/**
* ( , , )
*/
private Timestamp currentTime;
public RestResult() {
}
@Override
public String toString() {
return "RestResult{" +
"success=" + success +
", code='" + code + '\'' +
", data=" + data +
", errorMessage=" + errorMessage +
", currentTime=" + currentTime +
'}';
}
public RestResult(boolean success, String code, Object data, Object errorMessage) {
this.success = success;
this.code = code;
this.data = data;
this.errorMessage = errorMessage;
this.currentTime = new Timestamp(new DateTime().getMillis());
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(Object errorMessage) {
this.errorMessage = errorMessage;
}
public Timestamp getCurrentTime() {
return currentTime;
}
public void setCurrentTime(Timestamp currentTime) {
this.currentTime = currentTime;
}
}
ResponseBodyAdvice
package com.futao.springmvcdemo.foundation;
import com.alibaba.fastjson.JSONObject;
import com.futao.springmvcdemo.model.system.RestResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @author futao
* Created on 2018/9/22-20:24.
* Rest
*/
@ControllerAdvice(basePackages = "com.futao.springmvcdemo.controller")
public class RestResultWrapper implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
RestResult result = new RestResult(true, "0", body, null);
return JSONObject.toJSON(result);
}
}
@GetMapping("get")
public User get() {
User user = new User();
user.setUsername("NiuBist");
user.setId("123");
user.setAge("18");
user.setEmail("[email protected]");
user.setMobile("12312321312");
user.setAddress(" ");
return user;
}
결과:
2. 이상 처 리 를 통일 하고 이상 데이터 구 조 를 되 돌려 줍 니 다.
package com.futao.springmvcdemo.model.entity.constvar;
/**
* @author futao
* Created on 2018/9/21-15:29.
*
* : 01
* 001
*
*/
public final class ErrorMessage {
public static final String SYSTEM_EXCEPTION = " , ";
public static final String NOT_LOGIN = "01001_ , ";
public static final String MOBILE_ALREADY_REGISTER = "01002_ ";
public static final String LOGIC_EXCEPTION = "01003_ , ";
}
package com.futao.springmvcdemo.foundation;
/**
* @author futao
* Created on 2018/9/20-15:22.
*
*/
public class LogicException extends RuntimeException {
/**
*
*/
private String errorMsg;
/**
*
*/
private String code;
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private LogicException(String errorMsg) {
super(errorMsg);
this.code = errorMsg.substring(0, 5);
this.errorMsg = errorMsg.substring(6);
}
/**
*
*
* @param errorMsg
* @return
*/
public static LogicException le(String errorMsg) {
return new LogicException(errorMsg);
}
}
package com.futao.springmvcdemo.foundation;
import com.alibaba.fastjson.JSONObject;
import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage;
import com.futao.springmvcdemo.model.system.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author futao
* Created on 2018/9/21-15:13.
* ,
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Object logicExceptionHandler(HttpServletRequest request, Exception e, HttpServletResponse response) {
// , -1, ,
RestResult result = new RestResult(false, "-1", e.getMessage(), ErrorMessage.SYSTEM_EXCEPTION);
// ,
if (e instanceof LogicException) {
LogicException logicException = (LogicException) e;
result.setCode(logicException.getCode());
result.setErrorMessage(logicException.getErrorMsg());
} else {
//
logger.error(" :" + e.getMessage(), e);
}
return JSONObject.toJSON(result);
}
}
package com.futao.springmvcdemo.controller;
import com.futao.springmvcdemo.foundation.LogicException;
import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author futao
* Created on 2018/9/23-0:28.
*
*/
@RequestMapping(path = "exception", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class ExceptionTestController {
/**
*
*/
@GetMapping(path = "logicException")
public void logicException() {
throw LogicException.le(ErrorMessage.LOGIC_EXCEPTION);
}
/**
*
*/
@GetMapping(path = "systemException")
public void systemException() {
throw new NullPointerException(" , !!!");
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.