spring mvc 透传

随着公司的规模及项目的增多,会有一种透明传输的需求,而透明传输的这一层就用来做权限控制,灰度发布,流量统计。

实现透传需要注意的几点:

1.Spring MVC实现url通配,后端服务的url各式各样,并不能按照你所设想的长度,so,通配符能解决这个问题。

@RequestMapping(value = "/{serviceName}/{methodName}/**/", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
  public @ResponseBody Object getHttp(@PathVariable(value = "serviceName") String serviceName,
      @PathVariable(value = "methodName") String methodName, HttpServletRequest request,
      HttpServletResponse response) throws ServiceException {
    try {
      return sendGetHttp(serviceName, methodName, request, response);
    } catch (ServiceException e) {
      LOGGER.error("getHttp_service", e);
      response.setStatus(520);
      return ResponseEntity.fail(e.getErrorCode(), e.getErrorMessage());
    } catch (SystemException e) {
      LOGGER.error("getHttp_system", e);
      response.setStatus(520);
      return ResponseEntity.error(e.getErrorMessage());
    } catch (Exception e) {
      LOGGER.error("getHttp_exception", e);
      response.setStatus(520);
      return ResponseEntity.error(e.getMessage());
    }
  }

2.body流解析,POST/PUT/PATCH,一般都是包含body的请求,但是作为透明传输层,就是有那么一个不包含body,所以透明传输的请求不适合加上@RequestBody,这时body的信息,我们可以通过HttpServletRequest解析出来。

  // request中解析出body
  private String resolveRequestToBody(HttpServletRequest request) throws IOException {
    int length = request.getContentLength();
    String requestStr = null;
    if (length != 0) {
      InputStream inputStream = request.getInputStream();
      byte b[] = new byte[length];
      inputStream.read(b);
      inputStream.close();
      requestStr = new String(b);
      LOGGER.info("requestLength:" + length + ",requestType:" + request.getContentType() + ",body:"
          + requestStr);
    }
    return requestStr;
  }

 

 

附:

通配符详解推荐一篇博客:http://www.codeweblog.com/springmvc%E7%AC%94%E8%AE%B0%E7%B3%BB%E5%88%97-5-requestmapping%E8%AF%B7%E6%B1%82value%E7%9A%84%E9%80%9A%E9%85%8D%E7%AC%A6%E8%AF%A6%E8%A7%A3/

转载于:https://www.cnblogs.com/xiaoyuanwu/p/5292110.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值