您的位置:首页 > 编程语言 > Java开发

java学习笔记11 - 使用forward实现API接口转发

2013-03-05 14:01 671 查看
在做一个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;
}


这样就ok了,原来的具体controller不用做任何改动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: