PS怎么ps制作特效文字白云文字

java ajax长连接请求服务器数据 - 推酷
java ajax长连接请求服务器数据
Comet另一种形式为长轮询(long polling),客户端会与服务器建立一个持久的连接,直到服务器端有数据发送过来,服务器端断开,客户端处理完推送的数据,会再次发起一个持久的连接,循环往复。
和流(Streaming)区别主要在于,在一次长连接中,服务器端只推送一次,然后断开连接。
其实现形式大概可分文AJAX长轮询和JAVASCRIPT轮询两种。
AJAX方式请求长轮询
服务器端可以返回原始的数据,或格式化的JSON、XML、JAVASCRIPT信息,客户端可拥有更多的处理自由。在形式上和传统意义上的AJAX GET方式大致一样,只不过下一次的轮询需要等到上一次的轮询数据返回处理完方可进行。
这里给出客户端的小示范:
&!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/ charset=UTF-8&&&title&jQuery 1.5 with long poll&/title&&/head&&body&&div id=&tip&&&/div&&script type=&text/javascript& src=&/ajax/jQuery/jquery-1.5.min.js&&&/script&&script type=&text/javascript&&$(function (){ function log(resp){
$(&#tip&).html(&&b&& + resp + &&/b&&); }
log(&loading&);
// 去除缓存
$.ajaxSetup({ cache: false }); function initGet(){
$.get(&getNextTime&)
.success(function(resp){
log(resp);
}).error(function(){
log(&ERROR!&);
}).done(initGet); }
initGet();});&/script&&/body&&/html& 基于jQuery 1.5,事件链,比以往更简洁明了,尤其是在 done 方法中又一次调用自身,棒极了。
服务器端很简单,每1秒输出一次当前系统时间:
/** * 简单模拟每秒输出一次当前系统时间,精细到毫秒 *
* @author yongboy * @date
* @version 1.0 */@WebServlet(&/getNextTime&)public class GetNextTimeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
response.setContentType(&text/plain&);
PrintWriter out = response.getWriter();
out.print(DateFormatUtils.format(System.currentTimeMillis(),
&yyyy-MM-dd HH:mm:ss SSS&));
out.flush();
out.close(); }}
JAVASCRIPT标签轮询(Script tag long polling)
引用的JAVASCRIPT脚本文件是可以跨域的,再加上
,更为强大了。
这里给出一个演示,实现功能类似上面。
客户端清单:
&!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/ charset=UTF-8&&&title&jQuery 1.5 with JSONP FOR Comet&/title&&/head&&body&&div id=&tip&&&/div&&script type=&text/javascript& src=&/ajax/jQuery/jquery-1.5.min.js&&&/script&&script type=&text/javascript&&$(function (){ function log(resp){
$(&#tip&).html(&&b&&
&&/b&&); }
log(&loading&); function jsonp(){
$.getJSON('http://192.168.0.99:8080/servlet3/getNextTime2?callback=?').success(function(resp){
log(&now time : &
}).done(jsonp);
// 以下方式也是合法的
$.getJSON('http://192.168.0.99:8080/servlet3/getNextTime2?callback=?',function(date){
log(date);
}).done(jsonp);
jsonp();});&/script&&/body&&/html& 服务器端清单:
/** * JSONP形式简单模拟每秒输出一次当前系统时间,精细到毫秒 * @author yongboy * @date
* @version 1.0 */@WebServlet(&/getNextTime2&)public class GetNextTimeServlet2 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
String callback = request.getParameter(&callback&);
if(StringUtils.isBlank(callback)){
callback = &showResult&;
PrintWriter out = response.getWriter();
StringBuilder resultBuilder = new StringBuilder();
resultBuilder
.append(callback)
.append(&('&)
.append(DateFormatUtils.format(System.currentTimeMillis(), &yyyy-MM-dd HH:mm:ss SSS&))
.append(&');&);
out.print(resultBuilder);
out.flush();
out.close(); }} 每次请求时,都会在HTML头部生成一个JS网络地址(实现跨域):
http://192.168.0.99:8080/servlet3/getNextTime2?callback=jQuery&_=7 我们不用指定,jquery会自动生成一个随机的函数名。
请求上面地址服务器端在有新的数据输出时,生成的回调JS函数:
jQuery(' 17:20:33 921'); 从下面截图可以看到这一点。
生成相应内容:
&不过,长连接情况下,浏览器认为当前JS文件还没有加载完,会一直显示正在加载中。
上面的JSONP例子太简单,服务器和客户端的连接等待时间不过1秒钟时间左右,若在真实环境下,需要设置一个超时时间。
以往可能会有人告诉你,在客户端需要设置一个超时时间,若指定期限内服务器没有数据返回,则需要通知服务器端程序,断开连接,然后自身再次发起一个新的连接请求。
但在Servlet 3.0 异步连接的规范中,我们就不用那么劳心费神,那般麻烦了。掉换个儿,让服务器端通知客户端超时啦,赶紧重新连接啊。
在前面几篇博客中,演示了一个伪真实场景,博客主添加博客,然后主动以流形式推送给终端用户。这里采用JSONP跨域长轮询连接形式。
&html&&head&&title&Comet JSONP %u63A8%uB%u8BD5&/title&
&meta http-equiv=&X-UA-Compatible& content=&IE=8& /&
&meta http-equiv=&content-type& content=&text/charset=UTF-8&/&&meta name=&author& content=&&/&&meta name=&keywords& content=&servlet3, comet, ajax&/&&meta name=&description& content=&&/&&link type=&text/css& rel=&stylesheet& href=&css/main.css&/&&script type=&text/javascript& src=&/ajax/jQuery/jquery-1.5.min.js&&&/script&&script type=&text/javascript&&String.prototype.template=function(){
return this.replace(/\{(\d )\}/g, function(m, i){
return args[i];
});}var html = '&div class=&logDiv&&'
'&div class=&contentDiv&&{0}&/div&'
'&div class=&tipDiv&&last date : {1}&/div&'
'&div class=&clear&& &/div&'
'&/div&';function showContent(json) { $(&#showDiv&).prepend(html.template(json.content, json.date));}function initJsonp(){ $.getJSON('http://192.168.0.99/servlet3/getjsonpnew?callback=?').success(function(json){
if(json.state == 1){
showContent(json);
initJsonp();
} }).done(initJsonp)
.error(function(){
alert(&error!&); });}$(function (){ initJsonp();});&/script&&/head&&body style=&margin: 0; overflow: hidden&&&div id=&showDiv& class=&inputStyle&&loading ...&/div&&/body&&/html&
服务器端接收长轮询连接请求:
/** * JSONP获取最新信息 *
* @author yongboy * @date
* @version 1.0 */@WebServlet(urlPatterns = &/getjsonpnew&, asyncSupported = true)public class GetNewJsonpBlogPosts extends HttpServlet { private static final long serialVersionUID = 656L; private static final Log log = LogFactory.getLog(GetNewJsonpBlogPosts.class); protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setHeader(&Cache-Control&, &private&);
response.setHeader(&Pragma&, &no-cache&);
response.setHeader(&Connection&, &Keep-Alive&);
response.setHeader(&Proxy-Connection&, &Keep-Alive&);
response.setContentType(&text/charset=UTF-8&);
response.setCharacterEncoding(&UTF-8&);
String timeoutStr = request.getParameter(&timeout&);
if (StringUtils.isNumeric(timeoutStr)) {
timeout = Long.parseLong(timeoutStr);
// 设置1分钟
timeout = 1L * 60L * 1000L;
(&new request ...&);
final HttpServletResponse finalResponse =
final HttpServletRequest finalRequest =
final AsyncContext ac = request.startAsync(request, finalResponse);
// 设置成长久链接
ac.setTimeout(timeout);
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
(&onComplete Event!&);
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
public void onTimeout(AsyncEvent event) throws IOException {
// 尝试向客户端发送超时方法调用,客户端会再次请求/blogpush,周而复始
(&onTimeout Event!&);
// 通知客户端再次进行重连
final PrintWriter writer = finalResponse.getWriter();
String outString = finalRequest.getParameter(&callback&)
+ &({state:0,error:'timeout is now'});&;
writer.println(outString);
writer.flush();
writer.close();
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
public void onError(AsyncEvent event) throws IOException {
(&onError Event!&);
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
public void onStartAsync(AsyncEvent event) throws IOException {
(&onStartAsync Event!&);
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.add(ac); }}
很显然,在有博客数据到达时,会通知到已注册的客户端。
注意,推送数据之后,需要调用当前的异步上下文complete()函数:
/** * 监听器单独线程推送到客户端 *
* @author yongboy * @date
* @version 1.0 */@WebListenerpublic class NewBlogJsonpListener implements ServletContextListener { private static final Log log = LogFactory.getLog(NewBlogListener.class); public static final BlockingQueue BLOG_QUEUE = new LinkedBlockingQueue(); public static final Queue ASYNC_AJAX_QUEUE = new ConcurrentLinkedQueue(); public void contextDestroyed(ServletContextEvent arg0) {
(&context is destroyed!&); } public void contextInitialized(ServletContextEvent servletContextEvent) {
(&context is initialized!&);
// 启动一个线程处理线程队列
new Thread(runnable).start(); } private Runnable runnable = new Runnable() {
public void run() {
boolean isDone =
while (isDone) {
if (!BLOG_QUEUE.isEmpty()) {
(&ASYNC_AJAX_QUEUE size : &
+ ASYNC_AJAX_QUEUE.size());
MicBlog blog = BLOG_QUEUE.take();
if (ASYNC_AJAX_QUEUE.isEmpty()) {
String targetJSON = buildJsonString(blog);
for (AsyncContext context : ASYNC_AJAX_QUEUE) {
if (context == null) {
(&the current ASYNC_AJAX_QUEUE is null now !&);
(context.toString());
PrintWriter out = context.getResponse().getWriter();
if (out == null) {
(&the current ASYNC_AJAX_QUEUE's PrintWriter is null !&);
out.println(context.getRequest().getParameter(
&callback&)
+ &(& + targetJSON + &);&);
out.flush();
// 通知,执行完成函数
} catch (Exception e) {
e.printStackTrace();
} }; private static String buildJsonString(MicBlog blog) {
Map&string, object=&&& info = new HashMap&string, object=&&&();
info.put(&state&, 1);
info.put(&content&, blog.getContent());
info.put(&date&,
DateFormatUtils.format(blog.getPubDate(), &HH:mm:ss SSS&));
JSONObject jsonObject = JSONObject.fromObject(info);
return jsonObject.toString(); }}
长连接的超时时间,有人贴切的形容为“心跳频率”,联动着两端,需要根据环境设定具体值。
JSONP方式无论是轮询还是长轮询,都是可以很容易把目标程序融合到第三方网站,当前的个人主页、博客等很多小挂件大多也是采用这种形式进行跨域获取数据的。
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致如何判断一个请求是否为AJAX请求 - 七彩阳光java - ITeye技术网站
博客分类:
&& 在一次做非常复杂的ajax应用时,如果一个会话已经超时,但是此时再通过ajax请求,那么ajax返回的则是一个登陆页面的html,那这下就惨了,页面上而已就乱了,那么,能否在java端,如拦截器里判断客户的的请求是否是ajax请求呢,经过查询,能.
&& 普通请求与ajax请求的报文头不一样,通过如下
String requestType = request.getHeader("X-Requested-With");
如果requestType能拿到值,并且值为XMLHttpRequest,表示客户端的请求为异步请求,那自然是ajax请求了,反之如果为null,则是普通的请求
浏览 32624
论坛回复 /
(39 / 19283)
报文头可以自己设置的。
严格的说,木有办法。
从收的地方想办法
你发送返回的如果是html
总有预期吧
目有达到预期的html
都是错的不加到到dom树上
airpeng 写道zwllxs 写道&& 能否在java端,如拦截器里判断客户的的请求是否是ajax请求呢
判断出来了你想怎么样?
我之前的处理是在前台里弄的,判断返回的是登陆页面就让他整个跳到登陆页面去
你这样的话,项目中所有的ajax请求所在的页面,都要去单独判断单独处理,并且如果新加了ajax请求模块,你又要去格外处理,如果项目中的ajax请求多了,开发和维护就麻烦了,
所以如果能在拦截器中一次性处理那就更好,目前我就是在拦截器中返回一个逻辑视图,然后在全局配置中,通过这个逻辑视图去指向一个页面。然后你可以在这个页面上任意发挥了,你可以将这个页面做成div弹框,你也可以直接简单写几个字,直接提醒用户去重新登陆,但是,在这里不能写js,因为异步响应返回的js,是不会被识别的
我对你的做法的理解是:如果是ajax请求,那么超时了就不跳转到登陆页面,而是跳到指定的页面,对吗?
如果要象我说的那样弄的话,可以把你的ajax封装成一个方法,以为每次调用的时候只需要传下相应的参数就行了,不知道可以否,另:像jquery这类的js框架不太熟,不知道它们的封装的ajax有没有可以借鉴的
zwllxs 写道&& 能否在java端,如拦截器里判断客户的的请求是否是ajax请求呢
判断出来了你想怎么样?
我之前的处理是在前台里弄的,判断返回的是登陆页面就让他整个跳到登陆页面去
你这样的话,项目中所有的ajax请求所在的页面,都要去单独判断单独处理,并且如果新加了ajax请求模块,你又要去格外处理,如果项目中的ajax请求多了,开发和维护就麻烦了,
所以如果能在拦截器中一次性处理那就更好,目前我就是在拦截器中返回一个逻辑视图,然后在全局配置中,通过这个逻辑视图去指向一个页面。然后你可以在这个页面上任意发挥了,你可以将这个页面做成div弹框,你也可以直接简单写几个字,直接提醒用户去重新登陆,但是,在这里不能写js,因为异步响应返回的js,是不会被识别的
&& 能否在java端,如拦截器里判断客户的的请求是否是ajax请求呢
判断出来了你想怎么样?
我之前的处理是在前台里弄的,判断返回的是登陆页面就让他整个跳到登陆页面去
fflame 写道呃,从安全角度说,会话过期以后,返回登录页面是应该的吧?换句话说,处理应该是前台分析一下返回值,并相应的处理吧?
个人意见。。。。
我也是这么处理的,会话过期返回相应的值,前台取到值并处理。
+1
& 上一页 1
浏览: 390936 次
来自: 上海
你好,我使用第一种方法在页面上引用一直报错,使用第二种方法没问 ...
你好,我遇到的问题是这样的:de.hybris.platfor ...
嗯,这个确实是的。
我找了很多资料,终于在您这看到了。谢谢了。顺便说一下:该pro ...
[color=orange][/color]sdfsdfsdf ...01:15 提问
Java模拟HTTP请求如何获取请求页面中ajax方法的返回值
我有一个AAA.JSP页面是通过加载百度的地图API的JS文件,再调用其中的ajax请求方法获取地理坐标。地理坐标在该ajax方法的返回参数中的。我现在需要在服务器端获取地理位置信息,因此我通过java程序模拟HTTP请求,去访问AAA.JSP,但因为ajax是异步的,模拟程序访问该页面的时候,其中的ajax方法还没执行结束,服务器就返回了该页面的静态HTML内容,导致我无法获取地理位置信息。请问如何让服务器端在ajax执行完毕之后再返回呢?或者有什么其他的方案能解决这个需求呢。
按赞数排序
参考以下帖子,试试
其他相似问题java 用ajax java后台传回值 -
- ITeye技术网站
用ajax java后台传回值,包括传json
public static final void sendAsJson(HttpServletResponse response, String str)
response.setContentType("application/charset=UTF-8");
if (null != str)
response.getWriter().write(str);
} catch (IOException e) {
e.printStackTrace();
public static final void sendAsText(HttpServletResponse response, String str)
response.setContentType("text/charset=UTF-8");
if (null != str)
response.getWriter().write(str);
} catch (IOException e) {
e.printStackTrace();
blackproof
浏览: 772784 次
来自: 北京
Good job !!
为啥EPHEMERAL_SEQUENTIAL类型的节点并没有自 ...
写道新手讨厌不贴整个工程代码的大侠需要 ...
新手讨厌不贴整个工程代码的大侠如何用java模拟ajax数据发送请求_Java教程_动态网站制作指南
如何用java模拟ajax数据发送请求
来源:人气:3373
import mons.httpclient.*;
import mons.httpclient.methods.*;
import mons.httpclient.params.HttpMethodP
import .io.*;
public class HttpClientTutorial {
ivate static String url = "http://10.129.39.149:8090//loginMgt/login.action";
public static void method(HttpClient client,String url,String body){
PostMethod
method = new PostMethod(url);
//"count":10,"ignoreCase":"false","paras":["a%"],"queryId":"getMenu"
NameValuePair[] postData = new NameValuePair[]{};
//postData[0] = new NameValuePair("count", 10);
method.setRequestBody(body);//addParameters(postData);
// Provide custom retry handler is necessary
/*method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));*/
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody,"utf-8"));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
String body ="[{\"userId\":1,\"pass\":1}]";
// Create a method instance.
method(client,url,body);
url = "http://10.129.39.149:8090/ajax/getInitValueArr.action";
body = "[{\"count\":10,\"ignoreCase\":\"false\",\"paras\":[\"a%\"],\"queryId\":\"getMenu\"}]";
method(client,url,body);
HttpClient c = new HttpClient();
HttpMethod m = new GetMethod();
String path =msnListPath+"?account="+userSimpleInfo.getMsnAccount()+"&type=msn&uid="+userSimpleInfo.getPassportId()+"&pwd="+userSimpleInfo.getMsnPassword();
m.setPath(path);
String response="";
int status = 0;
= c.executeMethod(m);
if(status == HttpStatus.SC_OK) {
byte[] rbytes = m.getResponseBody();
response = new String(rbytes,"UTF-8");
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
优质网站模板

我要回帖

更多关于 白云u盘启动制作工具 的文章

 

随机推荐