maven 專案(四) spring整合springMVC開發統一接入API(準備工作:第二部分)
阿新 • • 發佈:2019-01-06
介面虛擬碼流程(為啥是虛擬碼,這裡就是很一般的寫法,給人蔘考吧):
/** @Controller:宣告是springMVC的響應元件 @RequestMapping(value = "/apicenter"):定義介面路徑 */ @Controller public class ApiDispatchController { private final Log loger = LogFactory.getLog(ApiDispatchController.class);//載入日誌部分 private static final String API_ID = "apiId"; private static final String ACCESS_TOKEN = "token"; private static final String FUNCTION_CODE = "functioncode"; @SuppressWarnings({ "rawtypes" }) @RequestMapping(value = "/apicenter") public String apiDispatch(HttpServletRequest req, HttpServletResponse rsp) { ApiResponse apiRsp = null; try { ApiRequest apiReq = new ApiRequest(); ApiRequest sysReq = new ApiRequest(); Enumeration em = req.getParameterNames();//獲取請求引數 while (em.hasMoreElements()) { String name = (String) em.nextElement(); if (API_ID.equals(name) || FUNCTION_CODE.equals(name) || ACCESS_TOKEN.equals(name)) { sysReq.put(name, req.getParameter(name)); } String value = req.getParameter(name); apiReq.put(name, value); } apiRsp = this.checkParam(sysReq);//驗證(一般是驗證簽名) if (apiRsp != null) { return this.outputApiResponse(req, rsp, apiRsp); } apiReq.setApiId(req.getParameter(API_ID)); apiReq.setAccessToken(req.getParameter(ACCESS_TOKEN)); apiReq.setFunctionCode(req.getParameter(FUNCTION_CODE)); apiReq.setRequest(req); apiReq.setResponse(rsp); String functioncode = req.getParameter(FUNCTION_CODE); String[] tempArr = functioncode.split("\\.");// 目錄暫時以這種方法反射 if (tempArr != null && tempArr.length > 0) { String serviceFunctionCode = tempArr[0]; Object bean = SpringBeanProxy.getBeanByFunctionCode(serviceFunctionCode); Method method = SpringBeanProxy.getMethodByFunctionCode(functioncode); try { Object rspObj = method.invoke(bean, new Object[] { apiReq }); if (rspObj instanceof ApiResponse) { apiRsp = (ApiResponse) rspObj; } } catch (Exception e) { e.printStackTrace();//列印異常 apiRsp = new ApiResponse(RestResultEnum.INVOKE_ERROR); } } } catch (Exception e) { e.printStackTrace(); } if (apiRsp == null) { apiRsp = new ApiResponse(RestResultEnum.UNKNOW_ERROR); } return this.outputApiResponse(req, rsp, apiRsp);//構建返回 }