【使用forward实现API接口转发】

在做一个API项目的时候,跟同事讨论使用哪种形式的接口名称更合适,备选的方案有两种:

  最后我们选择第2种,但底层还是第1种,所以两咱方式都是可以正常访问的,提供给调用方的是第2咱形式,这样就只要ghost xp系统下载之家使用forward做下转发就行了,具体代码如下:

  [java] v

  @ResponseBody

  @RequestMapping(value="/openapi")

  public String index(HttpServletRequest request, HttpServletResponse response) {

  //获取参数

  String apiName = request.getParameter("api");

  String version = request.getParameter("v");

  //设置默认API名称

  if (StringUtils.isEmpty(apiName)) {

  apiName = "demo.hello";

  }

  //替换API名称中的.号为/

  apiName = StringUtils.replace(apiName, ".", "/");

  //设置ghost win7系统下载默认版本号

  if (StringUtils.isEmpty(version)) {

  version = "1";

  }

  //转发接口

  try {

  request.getRequestDispatcher("/openapi/v"+version+"/"+apiName).forward(request, response);

  } catch (Exception e) {

  //TODO log

  //TODO return error message

  }

  return null;

  }

  这样就ok了,原来的具体controller不用做任何改动。

你可能感兴趣的:(电脑小技巧)