1. 程式人生 > >springboot返回值國際化處理

springboot返回值國際化處理

一:啟動類內配置

二:國際化檔案

三,攔截器

package com.otcbi;

import com.otcbi.common.dto.OperateResult;
import com.otcbi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(basePackages={"com.otcbi"})
public class I18nResponseBodyAdvice implements ResponseBodyAdvice<Object> {

   protected Logger logger = LoggerFactory.getLogger(this.getClass());
   
   @Override
   public Object beforeBodyWrite(Object obj, MethodParameter method,
                                  MediaType type, Class<? extends HttpMessageConverter<?>> converter,
                                  ServerHttpRequest request, ServerHttpResponse response) {
      try {
         if(obj instanceof OperateResult){
            OperateResult result = (OperateResult) obj;
            String resultCode = result.getStatus();
            if(resultCode!= null){
               HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
               String i18nMsg = getMessage(req, resultCode);
               if(!StringUtils.isEmpty(i18nMsg)){
                  result.setMessage(i18nMsg);
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
         logger.error("返回值國際化攔截異常",e);
      }
      return obj;
   }

   @Override
   public boolean supports(MethodParameter arg0,
                            Class<? extends HttpMessageConverter<?>> arg1) {
      return true;
   }
   
   /**
    * 返回國際化的值
    * @param request
    * @param key
    * @return
    */
   public String getMessage(HttpServletRequest request, String key){
      String value = "";
      try {
         RequestContext requestContext = new RequestContext(request);
         value = requestContext.getMessage(key);
      }catch (Exception e){
         logger.error(e.getMessage(),e);
         value="";
      }
        return value;
    }

}

 

返回包裝類為:

package com.otcbi.common.dto;

import java.util.HashMap;
import java.util.Map;


public class OperateResult<T> {

   private String innerException;

   public String getInnerException() {
      return innerException;
   }

   public static Map<String, Object> renderPage(Page page, Object object) {
      Map<String, Object> reqMap = new HashMap<String, Object>();
      reqMap.put("page", page);
      reqMap.put("objects", object);
      return reqMap;
   }

   public Boolean success() {
      boolean flag = true;
      if (this.getData() == null && !this.getStatus().equalsIgnoreCase("200")) {
         flag = false;
      }
      return flag;
   }

   public OperateResult(T data) {
      this.status = "200";
      this.innerException = "";
      this.message = "";
      this.data = data;
   }

   public void setInnerException(String innerException) {
      this.innerException = innerException;
   }

   public OperateResult(String innerException, String message, T data) {
      super();
      this.innerException = innerException;
      this.message = message;
      this.data = data;
      this.status = "400";
   }

   public OperateResult(String innerException, String message, T data, String status) {
      super();
      this.innerException = innerException;
      this.message = message;
      this.data = data;
      this.status = status;
   }

   public OperateResult() {
      super();
   }

   private String status;
   private String message;

   public String getStatus() {
      return status;
   }

   public void setStatus(String status) {
      this.status = status;
   }

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }

   private T data;

   public T getData() {
      return data;
   }

   public void setData(T data) {
      this.data = data;
   }

   public static OperateResult getVersionErrorOp() {

      OperateResult opForVersion = new OperateResult();
      opForVersion.setData(null);
      opForVersion.setMessage("不支援請求的版本!");
      return opForVersion;
   }

   public static OperateResult getParametersNotCompleteErrorOp(String descript) {

      OperateResult opForVersion = new OperateResult();
      opForVersion.setData(null);
      opForVersion.setMessage(descript);
      return opForVersion;
   }

}