spring 獲取 返回的值,進行修改
阿新 • • 發佈:2019-01-14
因為專案的需要,要對反會的值進行處理,我使用的 spring
@ControllerAdvice 註解進行處理
以前的介面有一部分是返回string,所以要進行相容
package com.threeti.danfoss.base.interceptor; import javax.servlet.http.HttpServletRequest; 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.http.server.ServletServerHttpRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import org.springframework.web.servlet.support.RequestContext; import com.threeti.danfoss.base.entity.XaResult; @ControllerAdvice(basePackages ={"com.threeti.danfoss.base.controller","com.threeti.danfoss.business.controller"}) public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { //獲取當前處理請求的controller的方法 //String methodName=returnType.getMethod().getName(); /*// 不攔截/不需要處理返回值 的方法 String method= "loginCheck"; //如登入 //不攔截 if(method.equals(methodName)) { return false; }*/ return true; } /*@Override public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { // TODO Auto-generated method stub return null; }*/ @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if(body instanceof XaResult){ XaResult xr = (XaResult) body; String message = xr.getMessage();//獲取message ServletServerHttpRequest req = (ServletServerHttpRequest) request; HttpServletRequest httpReq = req.getServletRequest(); RequestContext myreq = new RequestContext(httpReq); try{ if(xr.getMsgParams() == null){ message = myreq.getMessage(message); }else{ message = myreq.getMessage(message,xr.getMsgParams()); } }catch(Exception e){ message=myreq.getMessage("defined"); } xr.setMessage(message); return xr; }else{ return String.valueOf(body); } } }
因為做的 介面大部分是用定義的物件 XaResult 返回
@ResponseBody @RequestMapping(value="findProductCodeByStation",method=RequestMethod.POST) public XaResult<List<ProductCode>> findProductCodeByStation( @RequestParam(value = "station") String station, HttpServletRequest request ) throws BusinessException{ //Long userId = WebUitl.getCmsLoginedUserId(request); return productCodeService.findProductCodeByStation(station); }