首页 技术 正文
技术 2022年11月13日
0 收藏 409 点赞 2,797 浏览 1868 个字

当一个项目膨大到无法进行整理时,而作为新负责维护的团队是非常苦恼的。对于想实现两个系统的数据访问,使用Ajax数据请求方式获取jsonp格式的数据

需要有前端jquery库文件。

前端代码通过jquery的处理方式如下:

$.ajax({
type : "get", //jquey是不支持post方式跨域的
async:false,
url : "http://192.168.0.113:8080/test/", //跨域请求的URL
dataType : "jsonp",
//传递给请求处理程序,用以获得jsonp回调函数名的参数名(默认为:callback)
jsonp: "callback",
//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
jsonpCallback:"success_jsonpCallback",
//成功获取跨域服务器上的json数据后,会动态执行这个callback函数
success : function(json){
alert(json.name);
}
});

这时候,我是通过原生servlet进行测试的,通过获取jsonp的参数callback就可以拿到这个方法名字。

public class ServletTest extends HttpServlet {    private final String gdtcUrl = "http://www.xxxxx
.cn/";
/**
* 毫秒
*/
private final long delayTime = 60 * 1000; /**
* 定时器
*/
private Timer mTimer = null; /**
* 缓存json
*/
private String cashJson = null; @Override
public void init() throws ServletException {
String params = getInitParameter("iniParam");
System.out.println(params); mTimer = new Timer();
mTimer.schedule(new TimerTask() { @Override
public void run() {
List<ModuleBean> datas = JdbcConnection.getFast5Hm();
cashJson = JSON.toJSONString(datas);
System.out.println("数据定时来了:" + cashJson);
}
}, 0, delayTime);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("GBK");
resp.setContentType("text/plain;charset=UTF-8");
String referer = req.getHeader("Referer");
System.out.println("来访地址:" + referer);
if (referer != null && referer.startsWith(gdtcUrl)) {
// 当缓存为空时,请求一次数据库
if (cashJson == null) {
cashJson = JSON.toJSONString(JdbcConnection.getFast5Hm());
}
        
String renderStr = req.getParameter("callback") + "(" + cashJson
+ ")";
resp.getWriter().write(renderStr); } else {
resp.getWriter().write("error of no authority");
}
resp.getWriter().flush();
}
}

上面这种方式利用了缓存策略,把查询的数据缓存下来,缓解了服务器压力

通过referer对访问地址进行安全限制。重要的是把json数据拼接成jsonp格式返回给了前端ajax那个callback回调方法

初次在项目上着手后台,希望以后能有更大的进步

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,965
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781