1、FlexServlet
package com.ohgrateboy;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class FlexServlet extends HttpServlet {
public FlexServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 判断浏览器请求是否是JSON的类型/application/json
if (request.getContentType().indexOf("application/json") == -1) {
return;
}
String msg = "Success";
int code = 200;
JSONObject jsonReq = parseRequest(request);// 将页面JSON转换成Java JSON。
JSONObject jsonRes = new JSONObject();// 实例化一个JSON格式的响应变量。
String serviceId = "";
if (!jsonReq.has("serviceId")) {// 判断该请求是否有serviceId标志
code = 401;
msg = "MissingServiceId";
} else {
try {
serviceId = jsonReq.getString("serviceId");
jsonRes.put("serviceId", serviceId);
dispatch(jsonReq, jsonRes);
} catch (JSONException e) {
e.printStackTrace();
}
}
writeToResponse(response, jsonRes);
}
private void dispatch(JSONObject jsonReq, JSONObject jsonRes)
throws JSONException {
String msg = "";
int code = 200;
System.out.println("ServiceId = "+jsonReq.getString("serviceId"));
if(jsonReq.getString("serviceId").equalsIgnoreCase("simpleQuery")){
new SimpleQuery().exec(jsonReq,jsonRes);
}
// sv = (Service) wac.getBean(jsonReq.getString("serviceId"));
//实例化一个JavaBean处理请求
// sv.execute(jsonReq, jsonRes);
}
// 从JSON Request获取JSON Data添加IP后封装新的Java版的JSON对象实例。
public static JSONObject parseRequest(HttpServletRequest request) {
try {
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
InputStream ins = request.getInputStream();
InputStreamReader insr = new InputStreamReader(ins, encoding);
int readed = 0;
int size = request.getContentLength();
char[] buf = new char[size];
while (readed < size) {
int nextSize = size - readed;
int nextReaded = insr.read(buf, readed, nextSize);
if (nextReaded != -1) {
readed += nextReaded;
} else {
break;
}
}
System.out.println("Request JSON Value ="+ String.valueOf(buf));
JSONObject jsonReq = new JSONObject(String.valueOf(buf));
return jsonReq;
} catch (Exception e) {
}
return new JSONObject();
}
public static void writeToResponse(HttpServletResponse response,
JSONObject json) throws IOException {
response.addHeader("content-type", "text/javascript");
OutputStreamWriter out = new OutputStreamWriter(response
.getOutputStream(), "utf-8");
out.write(json.toString());
out.flush();
out.close();
}
public void init() throws ServletException {
}
}
2、SimpleQuery
package com.ohgrateboy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SimpleQuery {
public void exec(JSONObject jsonReq, JSONObject jsonRes) {
JSONArray body = new JSONArray();
try {
jsonRes.put("body", body);
JSONObject jsonRec = new JSONObject();
body.put(jsonRec);
jsonRec.put("id", "1");
jsonRec.put("name", "三国演义");
jsonRec.put("author", "罗贯中");
jsonRec.put("price", "59.30");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
3、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>FlexServlet</servlet-name>
<servlet-class>com.ohgrateboy.FlexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FlexServlet</servlet-name>
<url-pattern>/FlexServlet</url-pattern>
</servlet-mapping>
</web-app>
4、httpservice_json.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.rpc.http.HTTPService;
import com.bsoft.flex.util.JsonRequest;
import mx.controls.*;
import mx.collections.*;
private function doQuery():void
{
var obj:Object;
var cnd=[];
obj={serviceId: "simpleQuery",otherServer:"http://localhost:8090/flexweb/FlexServlet"};
JsonRequest.exec(obj, queryResultHandler);
}
public function queryResultHandler():void
{
var code:int=arguments[0];
var rs:Array=arguments[2]["body"] as Array;
var items:ArrayCollection=new ArrayCollection(rs);
if (code > 300)
{
var alert:Alert;
alert=Alert.show(arguments[1], "信息");
return;
}
if (items)
{
this.bookGrid.dataProvider = items;
}
}
]]>
</mx:Script>
<mx:DataGrid id="bookGrid">
<mx:columns>
<mx:DataGridColumn headerText="编号" dataField="id"/>
<mx:DataGridColumn headerText="书名" dataField="name"/>
<mx:DataGridColumn headerText="作者" dataField="author"/>
<mx:DataGridColumn headerText="价格" dataField="price"/>
</mx:columns>
</mx:DataGrid>
<mx:Button id="query" label="查 询" click="doQuery()" x="348" y="150"/>
</mx:Application>
5、JsonRequest.as
package com.bsoft.flex.util
{
import flash.events.HTTPStatusEvent;
import com.adobe.serialization.json.JSON;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.http.*;
import mx.controls.*;
public class JsonRequest
{
private static const CONTENT_TYPE:String = "application/json";
private static const METHOD:String = "POST";
private static const RES_CODE:String = "x-response-code";
private static const RES_MSG:String = "x-response-msg";
private static var SERVER_URL:String = "http://localhost/IS/";
public function JsonRequest()
{
return;
}
public static function set serverURL(url:String):void{
SERVER_URL = url;
return;
}
public static function exec(request:Object,fn:Function,arguments:Object=null,httpScope:Object=null):void{
var msg:String;
var code:int;
var json:Object;
var me:Object;
var req:* = request;
var callback:* = fn;
var args:* = arguments;
var scope:* = httpScope;
if(!req.url){
}
var requestUrl:String;
var conn:* = new HTTPService();
conn.url = SERVER_URL+requestUrl;
if(req.otherServer){
conn.url= req.otherServer;
}
conn.method = METHOD;
conn.contentType = CONTENT_TYPE;
if(!scope){
}
me = conn;
conn.addEventListener(ResultEvent.RESULT,function(event:ResultEvent):void
{
try{
json = JSON.decode(event.result.toString());
if(!json[RES_MSG])
{
}
msg = "SUCCESS";
if(!json[RES_CODE])
{
}
code = 200;
callback(code,msg,json);
}
catch(err:Error)
{
code = 500;
msg = "服务器请求失败:[ParseResponseError]";
try
{
callback.cal(me,code,msg,json,args);
}catch(err:Error){
Alert.show(err.toString());
}
}
return;
}
);
conn.addEventListener(HTTPStatusEvent.HTTP_STATUS,function(event:HTTPStatusEvent):void
{
code = 504;
msg = "服务器请求失败:[HTTPStatusEvent statusCode:]"+event.status+"]";
json[RES_CODE] = code;
json[RES_MSG] = msg;
callback.call(me,code,msg,json,args);
return;
}
);
conn.addEventListener(FaultEvent.FAULT,function(event:FaultEvent):void
{
code = 505;
msg = "服务器请求失败:[FaultEvent statusCode:]"+event.statusCode+"]";
json[RES_CODE] = code;
json[RES_MSG] = msg;
callback.call(me,code,msg,json,args);
return;
}
);
conn.send(JSON.encode(req));
return;
}
}
}
Tomcat控制台显示信息:
页面前端输出结果: