转载自:http://www.5180it.com/bbs/admin/1/117237.html
转载自:http://www.513school.com/bbs/admin/1/117237.html
记一个springboot项目拦截接口相应数据,并自定义修改数据内容的方法
在我们开发过程和前端联调数据,往往都没有好的测试数据,每次都做假的数据就太麻烦了,特别是一些报表数据。
现在分享一个可以自定义返回数据的方法,直接上代码
package com.yy.auth;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.yy.bs.demo.demodata.DemoDataService;
import com.yy.domain.bs.demo.demodata.DemoDataEntity;
import com.yy.frame.auth.handler.UserInfoThreadLocal;
import com.yy.modules.sys.param.ParamUtil;
import com.yy.modules.sys.user.UserInfo;
@ControllerAdvice
public class ResponseBodyAnalysis implements ResponseBodyAdvice
@Autowired
private DemoDataService demoDataService;
@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) {
try {
UserInfo curUser = UserInfoThreadLocal.getInstance().get();
if(curUser != null && curUser.getOrgid().equals(ParamUtil.getParamValue("demo_orgid", "1735292260538819520"))){
List
if(!CollectionUtils.isEmpty(list)){
return JSON.parseObject(list.get(0).getContent(), body.getClass());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return body;
}
}
这里我判断也比较简单,为不影响其他正常用户使用
先判断当前用户的机构是否指定的机构id,在判断有没配置对应的url
其中DemoDataEntity 里的字段也比较简单,如下
@Column(length = 256)
public String title;
@Column(length = 250)
public String url;
@Lob
public String content;
我们根据请求地址,找到对应的数据,然后直接转成对象返回即可
转载自:http://www.5180it.com/bbs/admin/1/117237.html
转载自:http://www.513school.com/bbs/admin/1/117237.html