---
title: "Thrift--JSClient"
author: "hanqunfeng"
date: "2013-09-26T14:45:01Z"
tags: []
categories: ["编程语言"]
slug: "thrift-jsclient"
draft: false
lastmod: "2013-09-26T14:48:58Z"
id: 1947627
url: "https://hanqunfeng.iteye.com/blog/1947627"
---

thrift提供了基于jquery--ajax的客户端调用方式，返回json数据。

生成js代码使用如下命令：

 

```
thrift --gen js Contact.thrift
```

这样会在gen-js目录下生成两个js文件：Contact\_types.js，ContactManager.js，将这两个js文件拷贝到项目中。

同时需要导入thrift.js（thrift-0.9.1\\lib\\js目录下）和JQuery.js（1.5以上的版本）。

 

 

编写一个jsp页面thriftJs.jsp，用于展示客户端的调用方法：

 

```
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="resources/js/thrift.js"></script>
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"></script>

<!-- ContactManager -->
<script type="text/javascript" src="resources/js/Contact_types.js"></script>
<script type="text/javascript" src="resources/js/ContactManager.js"></script>

<script type="text/javascript">
	$(function() {
		try {
			var path = "<%=request.getContextPath()%>";
			//使用ajax，不能跨域访问，这里传入一个type=json参数
			var transport = new Thrift.Transport(path + "/contractManageServletProxy.do?type=json");
			var protocol = new Thrift.Protocol(transport);
			var client = new ContactManagerClient(protocol);
			var result_GetString = client.getAll(); //json格式
			//alert(result_GetString);
			$("#thriftjs").html(result_GetString[0].id);
		} catch (e) {
			alert("出错鸟：" + e.message);
		}
	});
</script>

</head>
<body>
	thrift js result:
	<div id="thriftjs"></div>
</body>
</html>
```

 

 服务端依然使用[http://hanqunfeng.iteye.com/blog/1946999](/blog/1946999)中的servlet代理，只不过这里为了使其能够支持json类型，对代理进行了改写：

```
@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		TTransport inTransport = null;
		TTransport outTransport = null;
		TProtocolFactory inProtocolFactory = null;
		TProtocolFactory outProtocolFactory = null;
		String local_type = request.getParameter("type");

		try {
			
			if(StringUtils.hasText(local_type)){
				protocolType = local_type;
			}
			
			if ("json".equals(protocolType)) {//支持json协议
				inProtocolFactory = new TJSONProtocol.Factory();
				outProtocolFactory = new TJSONProtocol.Factory();
				response.setContentType("application/json");
			} else {
				inProtocolFactory = new TCompactProtocol.Factory();
				outProtocolFactory = new TCompactProtocol.Factory();
				response.setContentType("application/x-thrift");
			}
			

			if (null != this.customHeaders) {
				for (Map.Entry<String, String> header : this.customHeaders) {
					response.addHeader(header.getKey(), header.getValue());
				}
			}
			InputStream in = request.getInputStream();
			OutputStream out = response.getOutputStream();

			TTransport transport = new TIOStreamTransport(in, out);
			inTransport = transport;
			outTransport = transport;

			TProtocol inProtocol = inProtocolFactory.getProtocol(inTransport);
			TProtocol outProtocol = outProtocolFactory
					.getProtocol(outTransport);

			processor.process(inProtocol, outProtocol);
			out.flush();
		} catch (TException te) {
			throw new ServletException(te);
		}
	}
```