http开放接口,使用阿里巴巴fastjson返回Jason数据,解决跨域访问问题。

1、需求:

给工具开放一个接口,返回xml字符串,支持单个或批量

2、实现方式:

(1)通过http开放接口,第三方服务通过请求方式传参,服务根据传参响应,返回所需数据。

(2)采用阿里巴巴fastjson操作数据,返回json格式数据(键值对)。

 

web.xml配置servlet:

	
		SendData
		com.thunisoft.np.fy.api.SendData
	

	
            SendData
            *.senddata
        

Servlet功能代码:



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.thunisoft.artery.util.ArteryUtil;
import com.thunisoft.export15xml.ConfigManager;
import com.thunisoft.export15xml.SyncExportAjServiceImpl;
import com.thunisoft.export15xml.bean.TaskItem;

public class SendData extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private ConfigManager configManager;

    private static Logger logger = LoggerFactory.getLogger(SendData.class);

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

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

        configManager = (ConfigManager) ArteryUtil.getBean("configManager");

        //JSONObject相当于Map
        JSONObject jsonXmlData = new JSONObject();

        response.reset();
        /**
         * 设置响应头,允许所有跨域的请求访问:response.setHeader("Access-Control-Allow-Origin", "*");
         * 允许指定的跨域请求访问,例如:response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");
         */
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Content-type", "application/json;charset=utf-8");
        PrintWriter out = null;
        out = response.getWriter();

        if ("true".equals(configManager.getConfig("config.senddata"))) {
            //传参判空
            if (request.getParameter("N_AJBS") == null
                    || request.getParameter("C_BH") == null
                    || request.getParameter("N_JBFY") == null
                    || request.getParameter("N_YWLX") == null) {
                szXmlZt(jsonXmlData, false, "请检查传参");
                logger.error("传参问题");
            } else {
                String ywlx = request.getParameter("N_YWLX").toString();
                String ajlb = configManager.getAjlbMappings().get(ywlx);

       
                if (ajlb == null) {
                    szXmlZt(jsonXmlData, false, "错误");
                    logger.error("错误");
                } else {
                    TaskItem ti = new TaskItem(null,
                            request.getParameter("C_BH"),
                            Long.parseLong((request.getParameter("N_AJBS"))),
                            ajlb, Integer.parseInt(request
                                    .getParameter("N_JBFY")));

                    Map m = new SyncExportAjServiceImpl(
                            configManager).exportAjXml(ti, "np", false);
                    if (m.isEmpty()) {
                        szXmlZt(jsonXmlData, false, "没有符合条件的数据");
                        logger.error("请检查参数数据");
                    } else {
                        for (Iterator it = m.keySet().iterator(); it
                                .hasNext();) {
                            String xmlname = (String) it.next();
                            szXmlZt(jsonXmlData, true, "数据返回成功");
                            jsonXmlData.put("data", new String(m.get(xmlname),
                                    "utf-8"));
                            logger.info("数据返回成功");
                        }
                    }
                }
            }
        } else {
            szXmlZt(jsonXmlData, false, "该接口未启用");
            logger.info("senddata接口未启用");
        }
        out.print(jsonXmlData.toJSONString());
        out.flush();
        out.close();
    }

    /**
     * @param jsonXmlData
     */
    private void szXmlZt(JSONObject jsonXmlData, boolean str1, String str2) {
        jsonXmlData.put("success", str1);
        jsonXmlData.put("message", str2);
    }
}

前端测试代码:

index.xml



	
		
		
		
	
	
		
	

index.js

var data= {
				"C_BH_AJ":"BEAF2B9E14CD777A6E9A6E38DA3E5F9A",
				"N_AJBS":240000000821975,
				"C_AJLB":"0201",
				"N_JBFY":2400
	};
function Post(){
	$.ajax({
                   url: "http://172.23.20.35:8585/export15xml_frame/.senddata",
                   data: data,
                   type: "Post",
                   dataType: "json",
                   success: function (result) {
                       alert("请求成功!");
                   }
               })
}

 

你可能感兴趣的:(JavaEE开发,程序小工具)