注:此篇博文是本人看国外官方文档得来的,建议读者阅读原版英文。
1.client-server connection
先上一张图,如下
图1
对图1的说明:
- client与server建立一个连接,这种连接是底层的
- client发送request到server,等待server的answer
- server处理request,将处理结果返还给client,这个结果包括status code、其它data
在HTTP/1.1中,在步骤3执行完成后,connection不再被关闭,在connection有效的前提细,后面client不再需要执行步骤1,直接执行步骤2、3就可以。
为了进一步深入,如下图2,图2是我从国外的网上截下来的,建议读者阅读原文:
图2 HttpSession生成后会有个sessionID
- Client第一次发送请求,web container生成唯一的session ID(生成session ID的源码,如有兴趣,可以看下tomcat源码),并将其返回给client(在web container返回给client的response中),web container上的这个HttpSession是临时的。
- 后面Client在每次发送请求给服务器时,都将session ID发送给web container,这样web container就很容易区分出是哪个client.
- Web container使用这个session ID,找到对应的HttpSession,并将此次request与这个HttpSession联系起来。
1.1 web container中如何获得HttpSession
HttpServletRequest中的方法,如下图3所示:
/**
*
* Returns the current session associated with this request,
* or if the request does not have a session, creates one.
*
* @return the <code>HttpSession</code> associated
* with this request
*
* @see #getSession(boolean)
*
*/
public HttpSession getSession();
/**
*
* Returns the current <code>HttpSession</code>
* associated with this request or, if there is no
* current session and <code>create</code> is true, returns
* a new session.
*
* <p>If <code>create</code> is <code>false</code>
* and the request has no valid <code>HttpSession</code>,
* this method returns <code>null</code>.
*
* <p>To make sure the session is properly maintained,
* you must call this method before
* the response is committed. If the container is using cookies
* to maintain session integrity and is asked to create a new session
* when the response is committed, an IllegalStateException is thrown.
*
*
*
*
* @param create <code>true</code> to create
* a new session for this request if necessary;
* <code>false</code> to return <code>null</code>
* if there's no current session
*
*
* @return the <code>HttpSession</code> associated
* with this request or <code>null</code> if
* <code>create</code> is <code>false</code>
* and the request has no valid session
*
* @see #getSession()
*
*
*/
public HttpSession getSession(boolean create);
图3 获取HttpSession的方式
HttpSession中的方法如下图4所示,销毁HttpSession
/**
* Invalidates this session then unbinds any objects bound
* to it.
*
* @exception IllegalStateException if this method is called on an
* already invalidated session
*/
public void invalidate();
图4 销毁HttpSession
2.client-server model缺点
client-server model,如果client不发送请求,server不允许发送送数据给client。为了克服这个困难,开发者可以使用 XMLHTTPRequest请求服务器——即不断轮询服务器,或者WebSocket。
3.Cross-Origin Resource Sharing (CORS)
跨域资源共享。英文原版在这里。