你的位置:首页 > Java教程

[Java教程]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/