1. 程式人生 > >maven 專案(五) spring整合springMVC開發統一接入API--實現test介面

maven 專案(五) spring整合springMVC開發統一接入API--實現test介面

為什麼要採用測試介面的方式:貼完程式碼我再來說;

1.貼張圖片


2.是測試介面地址的暴露方式:

@Controller
public class ApiTestController {
	@Value("${epeit.api.server}")
	private String defaultApiServer;

	@Value("${epeit.api.id}")
	private String defaultApiId;

	@Value("${epeit.api.secert}")
	private String defaultApiSecret;

	@RequestMapping(value = "/apitest")
	public String apitest(ModelMap modelMap) {
		modelMap.addAttribute("defaultApiServer", defaultApiServer);
		modelMap.addAttribute("defaultApiId", defaultApiId);
		modelMap.addAttribute("defaultApiSecret", defaultApiSecret);
		modelMap.addAttribute("functionCodeCatalogMap", SpringBeanProxy.getFunctionCodeCatalogMap());
		modelMap.addAttribute("functionCodeListMap", SpringBeanProxy.getFunctionCodeListMap());
		return "/apitest";
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/doApiTest")
	public String doApiTest(HttpServletRequest req, HttpServletResponse rsp, @RequestParam String apiServer) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Enumeration em = req.getParameterNames();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			if ("apiServer".equals(name) || "apiSecret".equals(name) || "t".equals(name) || "paramName".equals(name) || "paramValue".equals(name)) {
				continue;
			}
			String value = req.getParameter(name);
			paramMap.put(name, value);
		}
        String secreyKey = req.getParameter("apiSecret");
        String token = SimpleTokenUtil.buildToken(paramMap, secreyKey);
		String[] paramNameArr = req.getParameterValues("paramName");
		String[] paramValueArr = req.getParameterValues("paramValue");
		if (paramNameArr != null && paramNameArr.length > 0) {
			int n = 0;
			for (String paramName : paramNameArr) {
				if (paramName != null && !"".equals(paramName.trim())) {
					paramMap.put(paramName, paramValueArr[n]);
				}
				n++;
			}
		}
		paramMap.put("debug", "true");
		paramMap.put("token", token);
		String retJson = HttpClientUtil.doHttpPost(apiServer + "/apicenter", paramMap);
		return WebHelper.outputJson(retJson, rsp);
	}
}
3. 請求引數:

{apiId=weizhan, functioncode=jdpush.selectJpushList, token=f45428f33e324d966c5e53d7aaba8eb3}

functioncode:會在我在前面提到的map中找到對應的介面地址,並呼叫;

4.控制檯列印結果:


5.採用什麼方式給APP端送回訊息:非常之常規的PrintWriter方式,列印輸出;

public static String output(String str, HttpServletResponse response, String contentType) {
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(str);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}