java学习笔记11 - 使用forward实现API接口转发
在做一个API项目的时候,跟同事讨论使用哪种形式的接口名称更合适,备选的方案有两种:
1. https://xxx.com/openapi/v1/demo/hello?a=aaa&b=bbb
2. https://xxx.com/openapi?api=demo.hello&v=1&a=aaa&b=bbb
最后我们选择第2种,但底层还是第1种,所以两咱方式都是可以正常访问的,提供给调用方的是第2咱形式,这样就只要使用forward做下转发就行了,具体代码如下:
@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, ".", "/");//设置默认版本号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;}