﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-wadise-随笔分类-Java</title><link>http://www.blogjava.net/wadise/category/5981.html</link><description /><language>zh-cn</language><lastBuildDate>Fri, 02 Mar 2007 03:36:16 GMT</lastBuildDate><pubDate>Fri, 02 Mar 2007 03:36:16 GMT</pubDate><ttl>60</ttl><item><title>DAO</title><link>http://www.blogjava.net/wadise/archive/2006/06/05/50607.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Mon, 05 Jun 2006 15:10:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/06/05/50607.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/50607.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/06/05/50607.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/50607.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/50607.html</trackback:ping><description><![CDATA[许多Java开发员已经知道DAO模式。这个模式有许多不同的实现，尽管如此，在这篇文章中将阐述DAO实现的设想：<br />1.系统中所有数据库访问都通过DAO来包装<br />2.每个DAO实例代表一个原生的领域对象或实体。如果一个领域对象有一个独立的生命周期，那么它应该有自己的DAO。<br />3.DAO代表在领域对象上的CURD操作。<br />4.DAO允许基于Criteria的查询不同于用主键查询。我比较倾向构造一个finder方法。该finder方法的返回值是一个领域对象组的Collection集合<br />5.DAO不代表处理事务，Sessions或连接。这些在DAO外处理将更加灵活。<br /><br />例子：<br />GenericDao是CRUD操作的DAO基类。<br /><div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">interface</span><span style="color: rgb(0, 0, 0);"> GenericDao </span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">T, PK </span><span style="color: rgb(0, 0, 255);">extends</span><span style="color: rgb(0, 0, 0);"> Serializable</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"> {<br /><br />    </span><span style="color: rgb(0, 128, 0);">/**</span><span style="color: rgb(0, 128, 0);"> Persist the newInstance object into database </span><span style="color: rgb(0, 128, 0);">*/</span><span style="color: rgb(0, 0, 0);"><br />    PK create(T newInstance);<br /><br />    </span><span style="color: rgb(0, 128, 0);">/**</span><span style="color: rgb(0, 128, 0);"> Retrieve an object that was previously persisted to the database using<br />     *   the indicated id as primary key<br />     </span><span style="color: rgb(0, 128, 0);">*/</span><span style="color: rgb(0, 0, 0);"><br />    T read(PK id);<br /><br />    </span><span style="color: rgb(0, 128, 0);">/**</span><span style="color: rgb(0, 128, 0);"> Save changes made to a persistent object.  </span><span style="color: rgb(0, 128, 0);">*/</span><span style="color: rgb(0, 0, 0);"><br />    </span><span style="color: rgb(0, 0, 255);">void</span><span style="color: rgb(0, 0, 0);"> update(T transientObject);<br /><br />    </span><span style="color: rgb(0, 128, 0);">/**</span><span style="color: rgb(0, 128, 0);"> Remove an object from persistent storage in the database </span><span style="color: rgb(0, 128, 0);">*/</span><span style="color: rgb(0, 0, 0);"><br />    </span><span style="color: rgb(0, 0, 255);">void</span><span style="color: rgb(0, 0, 0);"> delete(T persistentObject);<br />}</span></div><br /><br />下面是它的实现类：<br /><div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">class</span><span style="color: rgb(0, 0, 0);"> GenericDaoHibernateImpl </span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">T, PK </span><span style="color: rgb(0, 0, 255);">extends</span><span style="color: rgb(0, 0, 0);"> Serializable</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"><br />    </span><span style="color: rgb(0, 0, 255);">implements</span><span style="color: rgb(0, 0, 0);"> GenericDao</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">T, PK</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);">, FinderExecutor {<br />    </span><span style="color: rgb(0, 0, 255);">private</span><span style="color: rgb(0, 0, 0);"> Class</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">T</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"> type;<br /><br />    </span><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> GenericDaoHibernateImpl(Class</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">T</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"> type) {<br />        </span><span style="color: rgb(0, 0, 255);">this</span><span style="color: rgb(0, 0, 0);">.type </span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);"> type;<br />    }<br /><br />    </span><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> PK create(T o) {<br />        </span><span style="color: rgb(0, 0, 255);">return</span><span style="color: rgb(0, 0, 0);"> (PK) getSession().save(o);<br />    }<br /><br />    </span><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> T read(PK id) {<br />        </span><span style="color: rgb(0, 0, 255);">return</span><span style="color: rgb(0, 0, 0);"> (T) getSession().get(type, id);<br />    }<br /><br />    </span><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">void</span><span style="color: rgb(0, 0, 0);"> update(T o) {<br />        getSession().update(o);<br />    }<br /><br />    </span><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">void</span><span style="color: rgb(0, 0, 0);"> delete(T o) {<br />        getSession().delete(o);<br />    }<br />}</span></div><br /><br />扩展GenericDAO<br /><div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="color: rgb(0, 0, 255);">public</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">interface</span><span style="color: rgb(0, 0, 0);"> PersonDao </span><span style="color: rgb(0, 0, 255);">extends</span><span style="color: rgb(0, 0, 0);"> GenericDao</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">Person, Long</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"> {<br />    List</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">Person</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);"> findByName(String name);<br />}<br /></span></div><br /><img src ="http://www.blogjava.net/wadise/aggbug/50607.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-06-05 23:10 <a href="http://www.blogjava.net/wadise/archive/2006/06/05/50607.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Map的简易写法</title><link>http://www.blogjava.net/wadise/archive/2006/06/05/50598.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Mon, 05 Jun 2006 14:29:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/06/05/50598.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/50598.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/06/05/50598.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/50598.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/50598.html</trackback:ping><description><![CDATA[通常我们在初始化一个Map的时候，都要这样子：<br /><div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="color: rgb(0, 0, 0);">Map test </span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">new</span><span style="color: rgb(0, 0, 0);"> HashMap();<br />test.put(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">1</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">, </span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">11</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />test.put(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">2</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">, </span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">22</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);</span></div><br />这样就显得有点太繁烦，不像动态语言那么灵活。。但是我们可以这样写：<br /><div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="color: rgb(0, 0, 0);">Map test </span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);"> </span><span style="color: rgb(0, 0, 255);">new</span><span style="color: rgb(0, 0, 0);"> HashMap() {<br />  {<br />    put(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">1</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">, </span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">11</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />    put(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">2</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">, </span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">22</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />   }<br />};</span></div><br />Collection同理!<br /><img src ="http://www.blogjava.net/wadise/aggbug/50598.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-06-05 22:29 <a href="http://www.blogjava.net/wadise/archive/2006/06/05/50598.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpSession二（转载）</title><link>http://www.blogjava.net/wadise/archive/2006/05/09/45274.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Tue, 09 May 2006 12:27:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/05/09/45274.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/45274.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/05/09/45274.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/45274.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/45274.html</trackback:ping><description><![CDATA[原文：http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770<br /><br />Using Sessions and Session Persistence in Web Applications<a name="deploy-webapp"></a><p><a name="100367"></a>The following sections describe how to set up sessions and session persistence:</p><ul type="square"><p><a name="104397"></a></p><li type="square"><a href="http://e-docs.bea.com/wls/docs70/webapp/sessions.html#139518">Overview of HTTP Sessions</a><p><a name="139644"></a></p></li><li type="square"><a href="http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100659">Setting Up Session Management</a><p><a name="104409"></a></p></li><li type="square"><a href="http://e-docs.bea.com/wls/docs70/webapp/sessions.html#139726">Configuring Session Persistence</a><p><a name="104414"></a></p></li><li type="square"><a href="http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770">Using URL Rewriting</a></li></ul><p> </p><hr noshade="noshade" /><p class="head1"><a name="139518"></a>Overview of HTTP Sessions</p><p><a name="139531"></a>Session tracking enables you to track a user's
progress over multiple servlets or HTML pages, which, by nature, are
stateless. A session is defined as a series of related browser requests
that come from the same client during a certain time period. Session
tracking ties together a series of browser requests—think of these
requests as pages—that may have some meaning as a whole, such as a
shopping cart application.</p><p> </p><hr noshade="noshade" /><p class="head1"><a name="100659"></a>Setting Up Session Management <a name="session-management"></a></p><p><a name="100660"></a>WebLogic Server is set up to handle session
tracking by default. You need not set any of these properties to use
session tracking. However, configuring how WebLogic Server manages
sessions is a key part of tuning your application for best performance.
Tuning depends upon factors such as: </p><ul type="square"><p><a name="100661"></a></p><li type="square">How many users you expect to hit the servlet

<p><a name="100662"></a></p></li><li type="square">How many concurrent users hit the servlet 

<p><a name="100663"></a></p></li><li type="square">How long each session lasts 

<p><a name="100664"></a></p></li><li type="square">How much data you expect to store for each user 

<p><a name="139890"></a></p></li><li type="square">Heap size allocated to the WebLogic Server instance.
</li></ul><p class="head2"><a name="100665"></a>HTTP Session Properties<a name="session-props"></a></p><p><a name="100666"></a>You configure WebLogic Server session tracking with properties in the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>. For instructions on editing the WebLogic-specific deployment descriptor, see <a href="http://e-docs.bea.com/wls/docs70/webapp/webappdeployment.html#1031777">Step 4: Define session parameters</a>.</p><p><a name="100675"></a>For a complete list of session attributes, see <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1037041">jsp-descriptor</a>.</p><p><a name="141907"></a>WebLogic Server 7.0 introduced a change to the
SessionID format that caused some load balancers to lose the ability to
retain session stickiness. </p><p><a name="141908"></a>A new server startup flag,
-Dweblogic.servlet.useExtendedSessionFormat=true , retains the
information that the load-balancing application needs for session
stickiness. The extended session ID format will be part of the URL if
URL rewriting is activated, and the startup flag is set to true.</p><p class="head2"><a name="108118"></a>Session Timeout<a name="session-timeout"></a></p><p><a name="108122"></a>You can specify an interval of time after which
HTTP sessions expire. When a session expires, all data stored in the
session is discarded. You can set the interval in either web.xml or
weblogic.xml:</p><ul type="square"><p><a name="108125"></a></p><li type="square">Set the <font class="code">TimeoutSecs</font> attribute in the<a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1037041">jsp-descriptor</a> of the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml.</font> This value is set in seconds.

<p><a name="108223"></a></p></li><li type="square">Set the &lt;session-timeout&gt;(see <a href="http://e-docs.bea.com/wls/docs70/webapp/web_xml.html#1045373">session-config</a><font class="code">)</font><font class="code">element</font> in the Web Application deployment descriptor, <font class="code">web.xml</font>.
</li></ul><p class="head2"><a name="100676"></a>Configuring Session Cookies<a name="session-cookie"></a></p><p><a name="100677"></a>WebLogic Server uses cookies for session management when supported by the client browser. </p><p><a name="100678"></a>The cookies that WebLogic Server uses to track
sessions are set as transient by default and do not outlive the
session. When a user quits the browser, the cookies are lost and the
session lifetime is regarded as over. This behavior is in the spirit of
session usage and it is recommended that you use sessions in this way. </p><p><a name="109568"></a>You can configure session-tracking attributes of cookies in the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>. A complete list of session and cookie-related attributes is available <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1037041">jsp-descriptor</a>.</p><p><a name="109573"></a>For instructions on editing the WebLogic-specific deployment descriptor, see <a href="http://e-docs.bea.com/wls/docs70/webapp/webappdeployment.html#1031777">Step 4: Define session parameters</a>.</p><p class="head2"><a name="100688"></a>Using Cookies<a name="long-cookie"></a> That Outlive a Session</p><p><a name="100689"></a>For longer-lived client-side user data, your
application should create and set its own cookies on the browser via
the HTTP servlet API, and should not attempt to use the cookies
associated with the HTTP session. Your application might use cookies to
auto-login a user from a particular machine, in which case you would
set a new cookie to last for a long time. Remember that the cookie can
only be sent from that client machine. Your application should store
data on the server if it must be accessed by the user from multiple
locations.</p><p><a name="100690"></a>You cannot directly connect the age of a
browser cookie with the length of a session. If a cookie expires before
its associated session, that session becomes orphaned. If a session
expires before its associated cookie, the servlet is not be able to
find a session. At that point, a new session is assigned when the <font class="code">request.getSession(true)</font> method is called. You should only make transient use of sessions.</p><p><a name="139898"></a>You can set the maximum life of a cookie with the <font class="code">CookieMaxAgeSecs</font> parameter in the session descriptor of the <font class="code">weblogic.xml</font> deployment descriptor. For more information, see <a href="http://e-docs.bea.com/wls/docs70/webapp/webappdeployment.html#1031777">Step 4: Define session parameters</a></p><p class="head2"><a name="139365"></a>Logging Out and Ending a Session</p><p><a name="139397"></a>User authentication information is stored both
in the user's session data and in the context of a server or virtual
host that is targeted by a Web Application. The <font class="code">session.invalidate()</font>
method, which is often used to log out a user, only invalidates the
current session for a user—the user's authentication information still
remains valid and is stored in the context of the server or virtual
host. If the server or virtual host is hosting only one Web
Application, the <font class="code">session.invalidate() </font>method, in effect, logs out the user. </p><p><a name="139398"></a>There are several Java methods and strategies
you can use when using authentication with multiple Web Applications.
For more information, see <a href="http://e-docs.bea.com/wls/docs70/servlet/progtasks.html#sso">Implementing Single Sign-On</a> in the <em>Programming WebLogic HTTP Servlets</em>,.</p><p> </p><hr noshade="noshade" /><p class="head1"><a name="139726"></a>Configuring Session Persistence<a name="session-persistence"></a></p><p><a name="140566"></a>Use Session Persistence to permanently stored
data from an HTTP session object in order to enable failover and load
balancing across a cluster of WebLogic Servers. When your applications
stores data in an HTTP session object, the data must be serializable.</p><p><a name="139753"></a>There are five different implementations of session persistence: </p><ul type="square"><p><a name="100694"></a></p><li type="square">Memory (single-server, non-replicated) 

<p><a name="100695"></a></p></li><li type="square">File system persistence 

<p><a name="100696"></a></p></li><li type="square">JDBC persistence 

<p><a name="138904"></a></p></li><li type="square">Cookie-based session persistence

<p><a name="100697"></a></p></li><li type="square">In-memory replication (across a cluster) 
</li></ul><p><a name="100699"></a>The first four are discussed here; in-memory replication is discussed in <a href="http://e-docs.bea.com/wls/docs70/cluster/failover.html#1022034">"HTTP Session State Replication,"</a> in <em>Using WebLogic Server Clusters</em>.  </p><p><a name="100700"></a>File, JDBC, Cookie-based, and memory
(single-server, non-populated) session persistence have some common
properties. Each persistence method has its own set of attributes, as
discussed in the following sections.</p><p class="head2"><a name="100701"></a>Common Properties of Session Attributes<a name="common-props"></a></p><p><a name="100702"></a>This section describes attributes common to
file system, memory (single-server, non-replicated), JDBC, and
cookie-based persistence. You can configure the number of sessions that
are held in memory by setting the following properties in the <font class="code">&lt;session-descriptor&gt;</font> element of the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>. These properties are only applicable if you are using session persistence: </p><dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100706"></a><strong><font class="code">CacheSize</font></strong></dd></font></p><dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100707"></a>Limits
the number of cached sessions that can be active in memory at any one
time. If you are expecting high volumes of simultaneous active
sessions, you do not want these sessions to soak up the RAM of your
server since this may cause performance problems swapping to and from
virtual memory. When the cache is full, the least recently used
sessions are stored in the persistent store and recalled automatically
when required. If you do not use persistence, this property is ignored,
and there is no soft limit to the number of sessions allowed in main
memory. By default, the number of cached sessions is 1024. The minimum
is 16, and maximum is <em><font class="code">Integer.MAX_VALUE</font></em>. An empty session uses less than 100 bytes, but grows as data is added to it. </dd></font></p></dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100708"></a><strong><font class="code">SwapIntervalSecs</font></strong></dd></font></p><dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100709"></a>The interval the server waits between purging the least recently used sessions from the cache to the persistent store, when the <font class="code">cacheEntries</font> limit has been reached. </dd></font></p><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100710"></a>If unset, this property defaults to 10 seconds; minimum is 1 second, and maximum is 604800 (1 week). </dd></font></p></dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100711"></a><strong><font class="code">InvalidationIntervalSecs</font></strong></dd></font></p><dl><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="107731"></a>Sets
the time, in seconds, that WebLogic Server waits between doing
house-cleaning checks for timed-out and invalid sessions, and deleting
the old sessions and freeing up memory. Set this parameter to a value
less than the value set for the <font class="code">&lt;session-timeout&gt;</font> element. Use this parameter to tune WebLogic Server for best performance on high traffic sites.</dd></font></p><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="100713"></a>The
minimum value is every second (1). The maximum value is once a week
(604,800 seconds). If unset, the parameter defaults to 60 seconds.</dd></font></p><p><font color="#000000" face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="-1"><dd><a name="109632"></a>To set <font class="code">&lt;session-timeout&gt;, see</font> the <a href="http://e-docs.bea.com/wls/docs70/webapp/web_xml.html#1045373">session-config</a> of the Web Application deployment descriptor <font class="code">web.xml</font>. </dd></font></p></dl></dl><p class="head2"><a name="100714"></a>Using Memory-based, Single-server, Non-replicated Persistent Storage<a name="memoy-persistence"></a></p><p><a name="100715"></a>To use memory-based, single-server, non-replicated persistent storage, set the <font class="code">PersistentStoreType</font> property in the <font class="code">&lt;session-descriptor&gt;</font> element of the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font> to <font class="code">memory.</font>
When you use memory-based storage, all session information is stored in
memory and is lost when you stop and restart WebLogic Server.</p><p><a name="139953"></a><strong>Note:	</strong> If you do not allocate sufficient heap size when running WebLogic Server, your server may run out of memory under heavy load.</p><p class="head2"><a name="100716"></a>Using File-based Persistent Storage <a name="file_persistence"></a></p><p><a name="100717"></a>To configure file-based persistent storage for sessions: </p><ol type="1"><li value="1"><a name="100718"></a>Set the <font class="code">PersistentStoreType</font> property in the <font class="code">&lt;session-descriptor&gt;</font> element in the deployment descriptor file  <font class="code">weblogic.xml</font> to <font class="code">file</font>.
</li><li value="2"><a name="107755"></a>Set the directory where WebLogic Server stores the sessions. See <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036948">PersistentStoreDir</a>. <p><a name="107859"></a> If you do not explicitly set a value for this attribute, a temporary directory is created for you by WebLogic Server. </p><p><a name="113930"></a> If you are using file-based persistence in a
cluster, you must explicitly set this attribute to a shared directory
that is accessible to all the servers in a cluster. You must create
this directory yourself.</p></li></ol><p class="head2"><a name="113932"></a>Using a Database for Persistent <a name="jdbc_persistence"></a>Storage (JDBC persistence)</p><p><a name="139756"></a>JDBC persistence stores session data in a
database table using a schema provided for this purpose. You can use
any database for which you have a JDBC driver. You configure database
access by using connection pools.</p><p><a name="113933"></a>To configure JDBC-based persistent storage for sessions: </p><ol type="1"><li value="1"><a name="100724"></a>Set the <font class="code">PersistentStoreType</font> property in the <font class="code">&lt;session-descriptor&gt;</font> element of the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>, to <font class="code">jdbc.</font></li><li value="2"><a name="100725"></a>Set a JDBC connection pool to be used for persistence storage with the <font class="code">PersistentStorePool</font> property of the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>. Use the name of a connection pool that is defined in the WebLogic Server Administration Console.  <dl><dt></dt><p class="listpara"><a name="100731"></a>For more details on setting up a database connection pool, see <a href="http://e-docs.bea.com/wls/docs70/adminguide/jdbc.html">Managing JDBC Connectivity</a>.</p></dl></li><li value="3"><a name="100733"></a>Set an ACL for the
connection that corresponds to the users that have permission. For more
details on setting up a database connection, see <a href="http://e-docs.bea.com/wls/docs70/adminguide/jdbc.html">Managing JDBC Connectivity</a>.
</li><li value="4"><a name="140305"></a>Set up a database table named <font class="code">wl_servlet_sessions</font>
for JDBC-based persistence. The connection pool that connects to the
database needs to have read/write access for this table. The following
table shows the Column names and data types you should use when
creating this table.</li></ol><p><a name="140384"></a><strong><div class="tblmargin"><table bordercolorlight="#FFFFFF" bordercolordark="#000000" border="1" cellpadding="3" cellspacing="0"><tbody><tr bgcolor="#cccccc"><th align="left" valign="top"><b><p class="table"><a name="140388"></a><strong>Column name</strong></p></b></th><th align="left" valign="top"><b><p class="table"><a name="140390"></a><strong>Type</strong></p></b></th></tr><tr><td align="left" valign="top"><p class="table"><a name="140392"></a><font class="code">wl_id</font></p></td><td align="left" valign="top"><p class="table"><a name="140394"></a> Variable-width alphanumeric column, up to 100 characters; for example, Oracle <font class="code">VARCHAR2(100)</font>.<br /><em> The primary key must be set as follows:</em></p><p class="table"><a name="140395"></a><font class="code">wl_id + wl_context_path.</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140397"></a><font class="code">wl_context_path</font></p></td><td align="left" valign="top"><p class="table"><a name="140399"></a>Variable-width alphanumeric column, up to 100 characters; for example, Oracle <font class="code">VARCHAR2(100)</font>. <em>This column is used as part of the primary key. (See the </em><font class="code">wl_id</font><em>column</em><em> description.)</em></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140401"></a><font class="code">wl_is_new</font></p></td><td align="left" valign="top"><p class="table"><a name="140403"></a>Single char column; for example, Oracle <font class="code">CHAR(1)</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140405"></a><font class="code">wl_create_time</font></p></td><td align="left" valign="top"><p class="table"><a name="140407"></a>Numeric column, 20 digits; for example, Oracle <font class="code">NUMBER(20)</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140409"></a><font class="code">wl_is_valid</font></p></td><td align="left" valign="top"><p class="table"><a name="140411"></a>Single char column; for example, Oracle <font class="code">CHAR(1)</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140413"></a><font class="code">wl_session_values</font></p></td><td align="left" valign="top"><p class="table"><a name="140415"></a>Large binary column; for example, Oracle <font class="code">LONG RAW</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140417"></a><font class="code">wl_access_time</font></p></td><td align="left" valign="top"><p class="table"><a name="140419"></a>Numeric column, 20 digits; for example, <font class="code">NUMBER(20)</font></p></td></tr><tr><td align="left" valign="top"><p class="table"><a name="140421"></a><font class="code">wl_max_inactive_interval</font></p></td><td align="left" valign="top"><p class="table"><a name="140423"></a>Integer column; for example, Oracle <font class="code">Integer</font>.
Number of seconds between client requests before the session is
invalidated. A negative time value indicates that the session should
never timeout.</p></td></tr></tbody></table></div></strong></p><p><a name="140345"></a>If you are using an Oracle DBMS, use the following SQL statement to create the <font class="code">wl_servlet_sessions</font> table:</p><blockquote><pre><font color="#000000" face="Courier"><a name="119416"></a>create table wl_servlet_sessions<br />  ( wl_id VARCHAR2(100) NOT NULL,<br />    wl_context_path VARCHAR2(100) NOT NULL,<br />    wl_is_new CHAR(1),<br />    wl_create_time NUMBER(20),<br />    wl_is_valid CHAR(1),<br />    wl_session_values LONG RAW,<br />    wl_access_time NUMBER(20),<br />    wl_max_inactive_interval INTEGER,<br />   PRIMARY KEY (wl_id, wl_context_path) ); <br /></font></pre></blockquote><p><a name="141957"></a>If you are using SqlServer2000, use the following SQL statement to create the <font class="code">wl_servlet_sessions</font> table:</p><blockquote><pre><font color="#000000" face="Courier"><a name="141958"></a>create table wl_servlet_sessions<br />  ( wl_id VARCHAR2(100) NOT NULL,<br />    wl_context_path VARCHAR2(100) NOT NULL,<br />    wl_is_new VARCHAR(1),<br />    wl_create_time DeCIMAL,<br />    wl_is_valid VARCHAR(1),<br />    wl_session_values IMAGE,<br />    wl_access_time DECIMAL,<br />    wl_max_inactive_interval INTEGER,<br />   PRIMARY KEY (wl_id, wl_context_path) ); <br /></font></pre></blockquote><p><a name="119429"></a>Modify one of the preceeding SQL statements for use with your DBMS.</p><p><a name="119417"></a><strong>Note:	</strong> You can configure a
maximum duration that JDBC session persistence should wait for a JDBC
connection from the connection pool before failing to load the session
data with the <font class="code">JDBCConnectionTimeoutSecs</font> attribute. For more information, see <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1037016">JDBCConnectionTimeoutSecs</a>.</p><p class="head2"><a name="138913"></a>Using Cookie-Based Session Persistence</p><p><a name="138914"></a>Cookie-based session persistence provides a
stateless solution for session persistence by storing all session data
in a cookie that is stored in the user's browser. Cookie-based session
persistence is most useful when you do not need to store large amounts
of data in the session. Cookie-based session persistence can make
managing your WebLogic Server installation easier because clustering
failover logic is not required. Because the session is stored in the
browser, not on the server, you can start and stop WebLogic Servers
without losing sessions.</p><p><a name="138928"></a>There are some limitations to cookie-based session persistence:</p><ul type="square"><p><a name="138949"></a></p><li type="square">You can store only string attributes in the session. If you store any other type of object in the session, an <font class="code">IllegalArgument</font> exception is thrown.

<p><a name="138968"></a></p></li><li type="square">You cannot flush the HTTP response (because the cookie must be written to the header data <em>before</em> the response is committed).

<p><a name="139155"></a></p></li><li type="square">If the content
length of the response exceeds the buffer size, the response is
automatically flushed and the session data cannot be updated in the
cookie. (The buffer size is, by default, 8192 bytes. You can change the
buffer size with the <font class="code">javax.servlet.ServletResponse.setBufferSize()</font> method.

<p><a name="138985"></a></p></li><li type="square">You can only use basic (browser-based) authentication.

<p><a name="139186"></a></p></li><li type="square">Session data is sent to the browser in clear text.

<p><a name="139191"></a></p></li><li type="square">The user's browser must be configured to accept cookies.

<p><a name="141838"></a></p></li><li type="square">You cannot use commas (,) in a string when using cookie-based session persistence or an exception occurs.
</li></ul><p><a name="138990"></a>To set up cookie-based session persistence:</p><ol type="1"><li value="1"><a name="139001"></a>In the <font class="code">&lt;session-descriptor&gt;</font> element of <font class="code">weblogic.xml</font>, set the <font class="code">PersistentStoreType</font> parameter to <font class="code">cookie.</font></li><li value="2"><a name="139037"></a>Optionally, set a name for the cookie using the <font class="code">PersistentStoreCookieName</font> parameter. The default is <font class="code">WLCOOKIE</font>.</li></ol><p> </p><hr noshade="noshade" /><p class="head1"><a name="100770"></a><a name="urlrewriting"></a>Using URL Rewriting<a name="url-rewriting"></a></p><p><a name="100771"></a>In some situations, a browser or wireless
device may not accept cookies, which makes session tracking using
cookies impossible. URL rewriting is a solution to this situation that
can be substituted automatically when WebLogic Server detects that the
browser does not accept cookies. URL rewriting involves encoding the
session ID into the hyper-links on the Web pages that your servlet
sends back to the browser. When the user subsequently clicks these
links, WebLogic Server extracts the ID from the URL address and finds
the appropriate <font class="code">HttpSession</font> when your servlet calls the <font class="code">getSession()</font> method. </p><p><a name="100773"></a>Enable URL rewriting in WebLogic Server by setting the <font class="code">URLRewritingEnabled</font> attribute in the WebLogic-specific deployment descriptor, <font class="code">weblogic.xml</font>, under the <font class="code">&lt;session-descriptor&gt;</font> element.<font class="code"></font>The default value for this attribute is <font class="code">true</font>. See <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1037027">URLRewritingEnabled</a>. </p><p class="head2"><a name="100777"></a>Coding Guidelines for URL Rewriting</p><p><a name="123231"></a>There are some general guidelines for how your code should handle URLs in order to support URL rewriting. </p><ul type="square"><p><a name="123247"></a></p><li type="square">Avoid writing a URL straight to the output stream, as shown here: 

<blockquote><pre><font color="#000000" face="Courier"><a name="100778"></a>out.println("&lt;a href=\"/myshop/catalog.jsp\"&gt;catalog&lt;/a&gt;");</font></pre></blockquote><dl><dt></dt><p class="listpara"><a name="100779"></a>Instead, use the <font class="code">HttpServletResponse.encodeURL()</font> method, for example:</p><blockquote><pre><font color="#000000" face="Courier"><a name="100780"></a>out.println("&lt;a href=\""<br />     + response.encodeURL("myshop/catalog.jsp") <br />     + "\"&gt;catalog&lt;/a&gt;");</font></pre></blockquote><dt></dt><p class="listpara"><a name="100781"></a>Calling the <font class="code">encodeURL()</font>
method determines if the URL needs to be rewritten, and if so, it
rewrites it by including the session ID in the URL. The session ID is
appended to the URL and begins with a semicolon.</p></dl><p><a name="100782"></a></p></li><li type="square">In addition to URLs that are returned as a response to WebLogic Server, also encode URLs that send redirects. For example: 

<blockquote><pre><font color="#000000" face="Courier"><a name="100783"></a>if (session.isNew())<br />  response.sendRedirect (response.encodeRedirectUrl(welcomeURL));  </font></pre></blockquote><dl><dt></dt><p class="listpara"><a name="100784"></a>WebLogic
Server uses URL rewriting when a session is new, even if the browser
does accept cookies, because the server cannot tell whether a browser
accepts cookies in the first visit of a session. </p></dl><p><a name="109664"></a></p></li><li type="square">Your servlet can determine whether a given session ID was received from a cookie by checking the Boolean returned from the <font class="code">HttpServletRequest.isRequestedSessionIdFromCookie()</font> method. Your application may respond appropriately, or simply rely on URL rewriting by WebLogic Server.
</li></ul><p class="head2"><a name="109666"></a>URL Rewriting and Wireless Access Protocol (WAP) <a name="wap"></a></p><p><a name="139999"></a>If you are writing a WAP application, you must
use URL rewriting because the WAP protocol does not support cookies. In
addition, some WAP devices have a 128-character limit on the length of
a URL (including parameters), which limits the amount of data that can
be transmitted using URL rewriting. To allow more space for parameters,
you can limit the size of the session ID that is randomly generated by
WebLogic Server. See <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036988">IDLength</a>.</p><img src ="http://www.blogjava.net/wadise/aggbug/45274.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-05-09 20:27 <a href="http://www.blogjava.net/wadise/archive/2006/05/09/45274.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HttpSession一（转载）</title><link>http://www.blogjava.net/wadise/archive/2006/05/09/45273.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Tue, 09 May 2006 12:26:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/05/09/45273.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/45273.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/05/09/45273.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/45273.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/45273.html</trackback:ping><description><![CDATA[原文：http://www.javaresearch.org/article/showarticle.jsp?column=106&amp;thread=45120<br /><br />摘要：虽然session机制在web应用程序中被采用已经很长时间了，但是仍然有很多人不清楚session机制的本质，以至不能正确的应用这一技术。
本文将详细讨论session的工作机制并且对在Java web application中应用session机制时常见的问题作出解答。<br /><br />目录：<br />一、术语session<br />二、HTTP协议与状态保持<br />三、理解cookie机制<br />四、理解session机制<br />五、理解javax.servlet.http.HttpSession<br />六、HttpSession常见问题<br />七、跨应用程序的session共享<br />八、总结<br />参考文档<br /><br />一、术语session<br />在我的经验里，session这个词被滥用的程度大概仅次于transaction，更加有趣的是transaction与session在某些语境下的含义是相同的。<br /><br />session，
中文经常翻译为会话，其本来的含义是指有始有终的一系列动作/消息，比如打电话时从拿起电话拨号到挂断电话这中间的一系列过程可以称之为一个
 session。有时候我们可以看到这样的话“在一个浏览器会话期间，...”，这里的会话一词用的就是其本义，是指从一个浏览器窗口打开到关闭这个期
间 ①。最混乱的是“用户（客户端）在一次会话期间”这样一句话，它可能指用户的一系列动作（一般情况下是同某个具体目的相关的一系列动作，比如从登录到
选购商品到结账登出这样一个网上购物的过程，有时候也被称为一个transaction），然而有时候也可能仅仅是指一次连接，也有可能是指含义①，其中
的差别只能靠上下文来推断②。<br /><br />然而当session一词与网络协议相关联时，它又往往隐含了“面向连接”和/或“保持状态”这样两个含
义， “面向连接”指的是在通信双方在通信之前要先建立一个通信的渠道，比如打电话，直到对方接了电话通信才能开始，与此相对的是写信，在你把信发出去的
时候你并不能确认对方的地址是否正确，通信渠道不一定能建立，但对发信人来说，通信已经开始了。“保持状态”则是指通信的一方能够把一系列的消息关联起
来，使得消息之间可以互相依赖，比如一个服务员能够认出再次光临的老顾客并且记得上次这个顾客还欠店里一块钱。这一类的例子有“一个
TCP session”或者 “一个POP3 session”③。<br /><br />而到了web服务器蓬勃发展的时代，session在web开发语
境下的语义又有了新的扩展，它的含义是指一类用来在客户端与服务器之间保持状态的解决方案④。有时候session也用来指这种解决方案的存储结构，如
“把xxx保存在session 里”⑤。由于各种用于web开发的语言在一定程度上都提供了对这种解决方案的支持，所以在某种特定语言的语境下，
session也被用来指代该语言的解决方案，比如经常把Java里提供的javax.servlet.http.HttpSession简称为
session⑥。<br /><br />鉴于这种混乱已不可改变，本文中session一词的运用也会根据上下文有不同的含义，请大家注意分辨。<br />在本文中，使用中文“浏览器会话期间”来表达含义①，使用“session机制”来表达含义④，使用“session”表达含义⑤，使用具体的“HttpSession”来表达含义⑥<br /><br />二、HTTP协议与状态保持<br />HTTP 
协议本身是无状态的，这与HTTP协议本来的目的是相符的，客户端只需要简单的向服务器请求下载某些文件，无论是客户端还是服务器都没有必要纪录彼此过去
的行为，每一次请求之间都是独立的，好比一个顾客和一个自动售货机或者一个普通的（非会员制）大卖场之间的关系一样。<br /><br />然而聪明（或者贪
心？）的人们很快发现如果能够提供一些按需生成的动态信息会使web变得更加有用，就像给有线电视加上点播功能一样。这种需求一方面迫使HTML逐步添加
了表单、脚本、DOM等客户端行为，另一方面在服务器端则出现了CGI规范以响应客户端的动态请求，作为传输载体的HTTP协议也添加了文件上载、
 cookie这些特性。其中cookie的作用就是为了解决HTTP协议无状态的缺陷所作出的努力。至于后来出现的session机制则是又一种在客户
端与服务器之间保持状态的解决方案。<br /><br />让我们用几个例子来描述一下cookie和session机制之间的区别与联系。笔者曾经常去的一家咖啡店有喝5杯咖啡免费赠一杯咖啡的优惠，然而一次性消费5杯咖啡的机会微乎其微，这时就需要某种方式来纪录某位顾客的消费数量。想象一下其实也无外乎下面的几种方案：<br />1、该店的店员很厉害，能记住每位顾客的消费数量，只要顾客一走进咖啡店，店员就知道该怎么对待了。这种做法就是协议本身支持状态。<br />2、发给顾客一张卡片，上面记录着消费的数量，一般还有个有效期限。每次消费时，如果顾客出示这张卡片，则此次消费就会与以前或以后的消费相联系起来。这种做法就是在客户端保持状态。<br />3、发给顾客一张会员卡，除了卡号之外什么信息也不纪录，每次消费时，如果顾客出示该卡片，则店员在店里的纪录本上找到这个卡号对应的纪录添加一些消费信息。这种做法就是在服务器端保持状态。<br /><br />由
于HTTP协议是无状态的，而出于种种考虑也不希望使之成为有状态的，因此，后面两种方案就成为现实的选择。具体来说cookie机制采用的是在客户端保
持状态的方案，而session机制采用的是在服务器端保持状态的方案。同时我们也看到，由于采用服务器端保持状态的方案在客户端也需要保存一个标识，所
以session机制可能需要借助于cookie机制来达到保存标识的目的，但实际上它还有其他选择。<br /><br />三、理解cookie机制 <br />cookie机制的基本原理就如上面的例子一样简单，但是还有几个问题需要解决：“会员卡”如何分发；“会员卡”的内容；以及客户如何使用“会员卡”。<br /><br />正统的cookie分发是通过扩展HTTP协议来实现的，服务器通过在HTTP的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的cookie。然而纯粹的客户端脚本如JavaScript或者VBScript也可以生成cookie。<br /><br />而cookie 
的使用是由浏览器按照一定的原则在后台自动发送给服务器的。浏览器检查所有存储的cookie，如果某个cookie所声明的作用范围大于等于将要请求的
资源所在的位置，则把该cookie附在请求资源的HTTP请求头上发送给服务器。意思是麦当劳的会员卡只能在麦当劳的店里出示，如果某家分店还发行了自
己的会员卡，那么进这家店的时候除了要出示麦当劳的会员卡，还要出示这家店的会员卡。<br /><br />cookie的内容主要包括：名字，值，过期时间，路径和域。<br />其中域可以指定某一个域比如.google.com，相当于总店招牌，比如宝洁公司，也可以指定一个域下的具体某台机器比如www.google.com或者froogle.google.com，可以用飘柔来做比。<br />路径就是跟在域名后面的URL路径，比如/或者/foo等等，可以用某飘柔专柜做比。<br />路径与域合在一起就构成了cookie的作用范围。<br />如
果不设置过期时间，则表示这个cookie的生命期为浏览器会话期间，只要关闭浏览器窗口，cookie就消失了。这种生命期为浏览器会话期的
 cookie被称为会话cookie。会话cookie一般不存储在硬盘上而是保存在内存里，当然这种行为并不是规范规定的。如果设置了过期时间，浏览
器就会把cookie保存到硬盘上，关闭后再次打开浏览器，这些cookie仍然有效直到超过设定的过期时间。<br /><br />存储在硬盘上的
cookie 可以在不同的浏览器进程间共享，比如两个IE窗口。而对于保存在内存里的cookie，不同的浏览器有不同的处理方式。对于IE，在一个打
开的窗口上按 Ctrl-N（或者从文件菜单）打开的窗口可以与原窗口共享，而使用其他方式新开的IE进程则不能共享已经打开的窗口的内存cookie；
对于 Mozilla Firefox0.8，所有的进程和标签页都可以共享同样的cookie。一般来说是用javascript的
window.open打开的窗口会与原窗口共享内存cookie。浏览器对于会话cookie的这种只认cookie不认人的处理方式经常给采用
session机制的web应用程序开发者造成很大的困扰。<br /><br />下面就是一个goolge设置cookie的响应头的例子<br />HTTP/1.1 302 Found<br />Location: <a href="http://www.google.com/intl/zh-CN/">http://www.google.com/intl/zh-CN/</a><br />Set-Cookie: PREF=ID=0565f77e132de138:NW=1:TM=1098082649:LM=1098082649:S=KaeaCFPo49RiA_d8; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com<br />Content-Type: text/html<br /><br /><br /><br /><br />这是使用HTTPLook这个HTTP Sniffer软件来俘获的HTTP通讯纪录的一部分<br /><br /><br /><br /><br />浏览器在再次访问goolge的资源时自动向外发送cookie<br /><br /><br /><br /><br />使用Firefox可以很容易的观察现有的cookie的值<br />使用HTTPLook配合Firefox可以很容易的理解cookie的工作原理。<br /><br /><br /><br /><br />IE也可以设置在接受cookie前询问<br /><br /><br /><br /><br />这是一个询问接受cookie的对话框。<br /><br />四、理解session机制<br />session机制是一种服务器端的机制，服务器使用一种类似于散列表的结构（也可能就是使用散列表）来保存信息。<br /><br />当
程序需要为某个客户端的请求创建一个session的时候，服务器首先检查这个客户端的请求里是否已包含了一个session标识 - 称为
 session id，如果已包含一个session id则说明以前已经为此客户端创建过session，服务器就按照session id把这个
 session检索出来使用（如果检索不到，可能会新建一个），如果客户端请求不包含session id，则为此客户端创建一个session并且生
成一个与此session相关联的session id，session id的值应该是一个既不会重复，又不容易被找到规律以仿造的字符串，这个
 session id将被在本次响应中返回给客户端保存。<br /><br />保存这个session id的方式可以采用cookie，这样在交互过程中
浏览器可以自动的按照规则把这个标识发挥给服务器。一般这个cookie的名字都是类似于SEEESIONID，而。比如weblogic对于web应用
程序生成的cookie，JSESSIONID=
 ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764，它的名字就是
 JSESSIONID。<br /><br />由于cookie可以被人为的禁止，必须有其他机制以便在cookie被禁止时仍然能够把session id
传递回服务器。经常被使用的一种技术叫做URL重写，就是把session id直接附加在URL路径的后面，附加方式也有两种，一种是作为URL路径的
附加信息，表现形式为<a href="http://...../xxx;jsessionid=">http://...../xxx;jsessionid=</a> ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764<br />另一种是作为查询字符串附加在URL后面，表现形式为<a href="http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng%21-145788764">http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764</a><br />这两种方式对于用户来说是没有区别的，只是服务器在解析的时候处理的方式不同，采用第一种方式也有利于把session id的信息和正常程序参数区分开来。<br />为了在整个交互过程中始终保持状态，就必须在每个客户端可能请求的路径后面都包含这个session id。<br /><br />另一种技术叫做表单隐藏字段。就是服务器会自动修改表单，添加一个隐藏字段，以便在表单提交时能够把session id传递回服务器。比如下面的表单<br />&lt;form name="testform" action="/xxx"&gt;<br />&lt;input type="text"&gt;<br />&lt;/form&gt;<br />在被传递给客户端之前将被改写成<br />&lt;form name="testform" action="/xxx"&gt;<br />&lt;input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764"&gt;<br />&lt;input type="text"&gt;<br />&lt;/form&gt;<br />这种技术现在已较少应用，笔者接触过的很古老的iPlanet6(SunONE应用服务器的前身)就使用了这种技术。<br />实际上这种技术可以简单的用对action应用URL重写来代替。<br /><br />在
谈论session机制的时候，常常听到这样一种误解“只要关闭浏览器，session就消失了”。其实可以想象一下会员卡的例子，除非顾客主动对店家提
出销卡，否则店家绝对不会轻易删除顾客的资料。对session来说也是一样的，除非程序通知服务器删除一个session，否则服务器会一直保留，程序
一般都是在用户做log off的时候发个指令去删除session。然而浏览器从来不会主动在关闭之前通知服务器它将要关闭，因此服务器根本不会有机会
知道浏览器已经关闭，之所以会有这种错觉，是大部分session机制都使用会话cookie来保存session id，而关闭浏览器后这个
 session id就消失了，再次连接服务器时也就无法找到原来的session。如果服务器设置的cookie被保存到硬盘上，或者使用某种手段改
写浏览器发出的HTTP请求头，把原来的session id发送给服务器，则再次打开浏览器仍然能够找到原来的session。<br /><br />恰恰是由于关闭浏览器不会导致session被删除，迫使服务器为seesion设置了一个失效时间，当距离客户端上一次使用session的时间超过这个失效时间时，服务器就可以认为客户端已经停止了活动，才会把session删除以节省存储空间。<br /><br />五、理解javax.servlet.http.HttpSession<br />HttpSession是Java平台对session机制的实现规范，因为它仅仅是个接口，具体到每个web应用服务器的提供商，除了对规范支持之外，仍然会有一些规范里没有规定的细微差异。这里我们以BEA的Weblogic Server8.1作为例子来演示。<br /><br />首
先，Weblogic Server提供了一系列的参数来控制它的HttpSession的实现，包括使用cookie的开关选项，使用URL重写的开关
选项，session持久化的设置，session失效时间的设置，以及针对cookie的各种设置，比如设置cookie的名字、路径、域，
 cookie的生存时间等。<br /><br />一般情况下，session都是存储在内存里，当服务器进程被停止或者重启的时候，内存里的session
也会被清空，如果设置了session的持久化特性，服务器就会把session保存到硬盘上，当服务器进程重新启动或这些信息将能够被再次使用，
 Weblogic Server支持的持久性方式包括文件、数据库、客户端cookie保存和复制。<br /><br />复制严格说来不算持久化保存，因为session实际上还是保存在内存里，不过同样的信息被复制到各个cluster内的服务器进程中，这样即使某个服务器进程停止工作也仍然可以从其他进程中取得session。<br /><br />cookie生存时间的设置则会影响浏览器生成的cookie是否是一个会话cookie。默认是使用会话cookie。有兴趣的可以用它来试验我们在第四节里提到的那个误解。<br /><br />cookie的路径对于web应用程序来说是一个非常重要的选项，Weblogic Server对这个选项的默认处理方式使得它与其他服务器有明显的区别。后面我们会专题讨论。<br /><br />关于session的设置参考[5] <a href="http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036869">http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036869</a><br /><br />六、HttpSession常见问题<br />（在本小节中session的含义为⑤和⑥的混合）<br /><br /><br />1、session在何时被创建<br />一
个常见的误解是以为session在有客户端访问时就被创建，然而事实是直到某server端程序调用
 HttpServletRequest.getSession(true)这样的语句时才被创建，注意如果JSP没有显示的使用 &lt;%
 @page session="false"%&gt; 关闭session，则JSP文件在编译成Servlet时将会自动加上这样一条语句
 HttpSession session = HttpServletRequest.getSession(true);这也是JSP中隐含的
 session对象的来历。<br /><br />由于session会消耗内存资源，因此，如果不打算使用session，应该在所有的JSP中关闭它。<br /><br />2、session何时被删除<br />综合前面的讨论，session在下列情况下被删除a.程序调用HttpSession.invalidate();或b.距离上一次收到客户端发送的session id时间间隔超过了session的超时设置;或c.服务器进程被停止（非持久session）<br /><br />3、如何做到在浏览器关闭时删除session<br />严格的讲，做不到这一点。可以做一点努力的办法是在所有的客户端页面里使用javascript代码window.oncolose来监视浏览器的关闭动作，然后向服务器发送一个请求来删除session。但是对于浏览器崩溃或者强行杀死进程这些非常规手段仍然无能为力。<br /><br />4、有个HttpSessionListener是怎么回事<br />你
可以创建这样的listener去监控session的创建和销毁事件，使得在发生这样的事件时你可以做一些相应的工作。注意是session的创建和销
毁动作触发listener，而不是相反。类似的与HttpSession有关的listener还有
 HttpSessionBindingListener，HttpSessionActivationListener和
 HttpSessionAttributeListener。<br /><br />5、存放在session中的对象必须是可序列化的吗<br />不是必需
的。要求对象可序列化只是为了session能够在集群中被复制或者能够持久保存或者在必要时server能够暂时把session交换出内存。在
 Weblogic Server的session中放置一个不可序列化的对象在控制台上会收到一个警告。我所用过的某个iPlanet版本如果
 session中有不可序列化的对象，在session销毁时会有一个Exception，很奇怪。<br /><br />6、如何才能正确的应付客户端禁止cookie的可能性<br />对所有的URL使用URL重写，包括超链接，form的action，和重定向的URL，具体做法参见[6]<br /><a href="http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770">http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770</a><br /><br />7、开两个浏览器窗口访问应用程序会使用同一个session还是不同的session<br />参见第三小节对cookie的讨论，对session来说是只认id不认人，因此不同的浏览器，不同的窗口打开方式以及不同的cookie存储方式都会对这个问题的答案有影响。<br /><br />8、如何防止用户打开两个浏览器窗口操作导致的session混乱<br />这
个问题与防止表单多次提交是类似的，可以通过设置客户端的令牌来解决。就是在服务器每次生成一个不同的id返回给客户端，同时保存在session里，客
户端提交表单时必须把这个id也返回服务器，程序首先比较返回的id与保存在session里的值是否一致，如果不一致则说明本次操作已经被提交过了。可
以参看《J2EE核心模式》关于表示层模式的部分。需要注意的是对于使用javascript window.open打开的窗口，一般不设置这个id，
或者使用单独的id，以防主窗口无法操作，建议不要再window.open打开的窗口里做修改操作，这样就可以不用设置。<br /><br />9、为什么在Weblogic Server中改变session的值后要重新调用一次session.setValue<br />做这个动作主要是为了在集群环境中提示Weblogic Server session中的值发生了改变，需要向其他服务器进程复制新的session值。<br /><br />10、为什么session不见了<br />排
除session正常失效的因素之外，服务器本身的可能性应该是微乎其微的，虽然笔者在iPlanet6SP1加若干补丁的Solaris版本上倒也遇到
过；浏览器插件的可能性次之，笔者也遇到过3721插件造成的问题；理论上防火墙或者代理服务器在cookie处理上也有可能会出现问题。<br />出现这一问题的大部分原因都是程序的错误，最常见的就是在一个应用程序中去访问另外一个应用程序。我们在下一节讨论这个问题。<br /><br />七、跨应用程序的session共享<br /><br />常
常有这样的情况，一个大项目被分割成若干小项目开发，为了能够互不干扰，要求每个小项目作为一个单独的web应用程序开发，可是到了最后突然发现某几个小
项目之间需要共享一些信息，或者想使用session来实现SSO(single sign on)，在session中保存login的用户信息，最自
然的要求是应用程序间能够访问彼此的session。<br /><br />然而按照Servlet规范，session的作用范围应该仅仅限于当前应用程序
下，不同的应用程序之间是不能够互相访问对方的session的。各个应用服务器从实际效果上都遵守了这一规范，但是实现的细节却可能各有不同，因此解决
跨应用程序session共享的方法也各不相同。<br /><br />首先来看一下Tomcat是如何实现web应用程序之间session的隔离的，从
 Tomcat设置的cookie路径来看，它对不同的应用程序设置的cookie路径是不同的，这样不同的应用程序所用的session id是不同
的，因此即使在同一个浏览器窗口里访问不同的应用程序，发送给服务器的session id也可以是不同的。<br /><br /><br />  <br /><br />根据这个特性，我们可以推测Tomcat中session的内存结构大致如下。<br /><br /><br /><br /><br />笔
者以前用过的iPlanet也采用的是同样的方式，估计SunONE与iPlanet之间不会有太大的差别。对于这种方式的服务器，解决的思路很简单，实
际实行起来也不难。要么让所有的应用程序共享一个session id，要么让应用程序能够获得其他应用程序的session id。<br /><br />iPlanet中有一种很简单的方法来实现共享一个session id，那就是把各个应用程序的cookie路径都设为/（实际上应该是/NASApp，对于应用程序来讲它的作用相当于根）。<br />&lt;session-info&gt;<br />&lt;path&gt;/NASApp&lt;/path&gt;<br />&lt;/session-info&gt;<br /><br />需
要注意的是，操作共享的session应该遵循一些编程约定，比如在session attribute名字的前面加上应用程序的前缀，使得
 setAttribute("name", "neo")变成setAttribute("app1.name", "neo")，以防止命名空间冲
突，导致互相覆盖。<br /><br /><br />在Tomcat中则没有这么方便的选择。在Tomcat版本3上，我们还可以有一些手段来共享
session。对于版本4以上的Tomcat，目前笔者尚未发现简单的办法。只能借助于第三方的力量，比如使用文件、数据库、JMS或者客户端
cookie，URL参数或者隐藏字段等手段。<br /><br />我们再看一下Weblogic Server是如何处理session的。<br /><br /><br />  <br /><br />从
截屏画面上可以看到Weblogic Server对所有的应用程序设置的cookie的路径都是/，这是不是意味着在Weblogic Server中
默认的就可以共享session了呢？然而一个小实验即可证明即使不同的应用程序使用的是同一个session，各个应用程序仍然只能访问自己所设置的那
些属性。这说明Weblogic Server中的session的内存结构可能如下<br /><br /><br /><br /><br />对于这样一种结构，在
 session机制本身上来解决session共享的问题应该是不可能的了。除了借助于第三方的力量，比如使用文件、数据库、JMS或者客户端
 cookie，URL参数或者隐藏字段等手段，还有一种较为方便的做法，就是把一个应用程序的session放到ServletContext中，这样
另外一个应用程序就可以从ServletContext中取得前一个应用程序的引用。示例代码如下，<br /><br />应用程序A<br />context.setAttribute("appA", session); <br /><br />应用程序B<br />contextA = context.getContext("/appA");<br />HttpSession sessionA = (HttpSession)contextA.getAttribute("appA"); <br /><br />值得注意的是这种用法不可移植，因为根据ServletContext的JavaDoc，应用服务器可以处于安全的原因对于context.getContext("/appA");返回空值，以上做法在Weblogic Server 8.1中通过。<br /><br />那
么Weblogic Server为什么要把所有的应用程序的cookie路径都设为/呢？原来是为了SSO，凡是共享这个session的应用程序都可
以共享认证的信息。一个简单的实验就可以证明这一点，修改首先登录的那个应用程序的描述符weblogic.xml，把cookie路径修改为
/appA 访问另外一个应用程序会重新要求登录，即使是反过来，先访问cookie路径为/的应用程序，再访问修改过路径的这个，虽然不再提示登录，但
是登录的用户信息也会丢失。注意做这个实验时认证方式应该使用FORM，因为浏览器和web服务器对basic认证方式有其他的处理方式，第二次请求的认
证不是通过 session来实现的。具体请参看[7] secion 14.8 Authorization，你可以修改所附的示例程序来做这些试验。<br /><br />八、总结<br />session机制本身并不复杂，然而其实现和配置上的灵活性却使得具体情况复杂多变。这也要求我们不能把仅仅某一次的经验或者某一个浏览器，服务器的经验当作普遍适用的经验，而是始终需要具体情况具体分析。<br />摘
要：虽然session机制在web应用程序中被采用已经很长时间了，但是仍然有很多人不清楚session机制的本质，以至不能正确的应用这一技术。本
文将详细讨论session的工作机制并且对在Java web application中应用session机制时常见的问题作出解答。<img src ="http://www.blogjava.net/wadise/aggbug/45273.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-05-09 20:26 <a href="http://www.blogjava.net/wadise/archive/2006/05/09/45273.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Adobe Acrobat 7.0下载地址，不是Adobe Acrobat Reader</title><link>http://www.blogjava.net/wadise/archive/2006/03/03/33497.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Fri, 03 Mar 2006 08:53:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/03/03/33497.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/33497.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/03/03/33497.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/33497.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/33497.html</trackback:ping><description><![CDATA[这个软件可以对PDF进行创建，编辑，加注释，评语等等。<BR>URL <A href="http://219.149.54.89/Software/SoftDown.asp?ID=33">http://219.149.54.89/Software/SoftDown.asp?ID=33</A><img src ="http://www.blogjava.net/wadise/aggbug/33497.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-03-03 16:53 <a href="http://www.blogjava.net/wadise/archive/2006/03/03/33497.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>如何把Hibernate2.1升级到Hibernate3.0？</title><link>http://www.blogjava.net/wadise/archive/2006/03/02/33114.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Thu, 02 Mar 2006 00:55:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2006/03/02/33114.html</guid><wfw:comment>http://www.blogjava.net/wadise/comments/33114.html</wfw:comment><comments>http://www.blogjava.net/wadise/archive/2006/03/02/33114.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/wadise/comments/commentRss/33114.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/wadise/services/trackbacks/33114.html</trackback:ping><description><![CDATA[<TABLE width="97%" border=0>
<TBODY>
<TR>
<TD width="94%">
<DIV align=left><FONT size=4>如何把Hibernate2.1升级到Hibernate3.0？ </FONT></DIV>
<P align=left><FONT size=2>选自&lt;&lt;精通Hibernate：Java对象持久化技术详解&gt;&gt; 作者：<A href="http://www.javathinker.org/main.jsp?bc=weiqin/weiqin.jsp"><FONT color=#996666>孙卫琴</FONT></A> 来源:www.javathinker.org<BR>如果转载，请标明出处，谢谢<BR></FONT></P></TD></TR>
<TR>
<TD width="94%">
<P><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#11"><FONT color=#999999>1.1 Hibernate API 变化 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#111"><FONT color=#999999>1.1.1 包名 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#112"><FONT color=#999999>1.1.2 org.hibernate.classic包 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#113"><FONT color=#999999>1.1.3 Hibernate所依赖的第三方软件包</FONT></A> <BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#114"><FONT color=#999999>1.1.4 异常模型 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#115"><FONT color=#999999>1.1.5 Session接口</FONT></A> <BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#116"><FONT color=#999999>1.1.6 createSQLQuery() </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#117"><FONT color=#999999>1.1.7 Lifecycle 和 Validatable 接口 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#118"><FONT color=#999999>1.1.8 Interceptor接口 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#119"><FONT color=#999999>1.1.9 UserType和CompositeUserType接口 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#1110"><FONT color=#999999>1.1.10 FetchMode类 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#1111"><FONT color=#999999>1.1.11 PersistentEnum类 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#1112"><FONT color=#999999>1.1.12 对Blob 和Clob的支持 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#1113"><FONT color=#999999>1.1.13 Hibernate中供扩展的API的变化 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#12"><FONT color=#999999>1.2 元数据的变化 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#121"><FONT color=#999999>1.2.1 检索策略 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#122"><FONT color=#999999>1.2.2 对象标识符的映射 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#123"><FONT color=#999999>1.2.3 集合映射 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#124"><FONT color=#999999>1.2.4 DTD</FONT></A> <BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#13"><FONT color=#999999>1.3 查询语句的变化 </FONT></A><BR><A href="http://www.javathinker.org/main.jsp?bc=hibernate/hibernate_version_upgrade.htm#131"><FONT color=#999999>1.3.1 indices()和elements()函数</FONT></A> </P>
<P><BR>尽管Hibernate 3.0 与Hibernate2.1的源代码是不兼容的，但是当Hibernate开发小组在设计Hibernate3.0时，为简化升级Hibernate版本作了周到的考虑。对于现有的基于Hibernate2.1的Java项目，可以很方便的把它升级到Hibernate3.0。<BR><BR>本文描述了Hibernate3.0版本的新变化，Hibernate3.0版本的变化包括三个方面：<BR>（1）API的变化，它将影响到Java程序代码。<BR>（2）元数据，它将影响到对象-关系映射文件。<BR>（3）HQL查询语句。<BR><BR>值得注意的是， Hibernate3.0并不会完全取代Hibernate2.1。在同一个应用程序中，允许Hibernate3.0和Hibernate2.1并存。<BR><BR><A name=11></A>1.1 Hibernate API 变化<BR><BR><A name=111></A>1.1.1 包名<BR><BR>Hibernate3.0的包的根路径为: “org.hibernate” ，而在Hibernate2.1中为“net.sf.hibernate”。这一命名变化使得Hibernate2.1和Hibernate3.0能够同时在同一个应用程序中运行。<BR><BR>如果希望把已有的应用升级到Hibernate3.0，那么升级的第一步是把Java源程序中的所有“net.sf.hibernate”替换为“org.hibernate”。<BR><BR>Hibernate2.1中的“net.sf.hibernate.expression”包被改名为“org.hibernate.criterion”。假如应用程序使用了Criteria API，那么在升级的过程中，必须把Java源程序中的所有“net.sf.hibernate.expression”替换为“org.hibernate.criterion”。<BR><BR>如果应用使用了除Hibernate以外的其他外部软件，而这个外部软件又引用了Hibernate的接口，那么在升级时必须十分小心。例如EHCache拥有自己的CacheProvider： net.sf.ehcache.hibernate.Provider，在这个类中引用了Hibernate2.1中的接口，在升级应用时，可以采用以下办法之一来升级EHCache:<BR><BR>（1）手工修改net.sf.ehcache.hibernate.Provider类，使它引用Hibernate3.0中的接口。<BR>（2）等到EHCache软件本身升级为使用Hibernate3.0后，使用新的EHCache软件。<BR>（3）使用Hibernate3.0中内置的CacheProvider：org.hibernate.cache.EhCacheProvider。<BR><BR><A name=112></A>1.1.2 org.hibernate.classic包<BR><BR>Hibernate3.0把一些被废弃的接口都转移到org.hibernate.classic中。<BR><BR><A name=113></A>1.1.3 Hibernate所依赖的第三方软件包<BR><BR>在Hibernate3.0的软件包的lib目录下的README.txt文件中，描述了Hibernate3.0所依赖的第三方软件包的变化。<BR><BR><A name=114></A>1.1.4 异常模型<BR><BR>在Hibernate3.0中，HibernateException异常以及它的所有子类都继承了java.lang.RuntimeException。因此在编译时，编译器不会再检查HibernateException。<BR><BR><A name=115></A>1.1.5 Session接口<BR><BR>在Hibernate3.0中，原来Hibernate2.1的Session接口中的有些基本方法也被废弃，但为了简化升级，这些方法依然是可用的，可以通过org.hibernate.classic.Session子接口来访问它们，例如：<BR></P>
<P><FONT size=2>org.hibernate.classic.Session session=sessionFactory.openSession();<BR>session.delete("delete from Customer ");<BR></FONT></P>
<P>在Hibernate3.0中，org.hibernate.classic.Session接口继承了org.hibernate.Session接口，在org.hibernate.classic.Session接口中包含了一系列被废弃的方法，如find()、interate()等。SessionFactory接口的openSession()方法返回org.hibernate.classic.Session类型的实例。如果希望在程序中完全使用Hibernate3.0，可以采用以下方式创建Session实例：<BR><BR><FONT size=2>org.hibernate.Session session=sessionFactory.openSession();</FONT><BR><BR>如果是对已有的程序进行简单的升级，并且希望仍然调用Hibernate2.1中Session的一些接口，可以采用以下方式创建Session实例：<BR><BR><FONT size=2>org.hibernate.classic.Session session=sessionFactory.openSession();</FONT><BR><BR>在Hibernate3.0中，Session接口中被废弃的方法包括：<BR>* 执行查询的方法：find()、iterate()、filter()和delete(String hqlSelectQuery) <BR>* saveOrUpdateCopy()<BR><BR>Hibernate3.0一律采用createQuery()方法来执行所有的查询语句，采用DELETE 查询语句来执行批量删除，采用merge()方法来替代 saveOrUpdateCopy()方法。</P>
<P><BR><I>提示：在Hibernate2.1中，Session的delete()方法有几种重载形式，其中参数为HQL查询语句的delete()方法在Hibernate3.0中被废弃，而参数为Ojbect类型的的delete()方法依然被支持。delete(Object o)方法用于删除参数指定的对象，该方法支持级联删除。</I></P>
<P>Hibernate2.1没有对批量更新和批量删除提供很好的支持，参见&lt;&lt;精通Hibernate&gt;&gt;一书的第13章的13.1.1节（批量更新和批量删除），而Hibernate3.0对批量更新和批量删除提供了支持，能够直接执行批量更新或批量删除语句，无需把被更新或删除的对象先加载到内存中。以下是通过Hibernate3.0执行批量更新的程序代码：</P>
<P><FONT size=2>Session session = sessionFactory.openSession();<BR>Transaction tx = session.beginTransaction();</FONT></P>
<P><FONT size=2>String hqlUpdate = "update Customer set name = :newName where name = :oldName";<BR>int updatedEntities = s.createQuery( hqlUpdate )<BR>.setString( "newName", newName )<BR>.setString( "oldName", oldName )<BR>.executeUpdate();<BR>tx.commit();<BR>session.close();</FONT></P>
<P>以下是通过Hibernate3.0执行批量删除的程序代码：</P>
<P><FONT size=2>Session session = sessionFactory.openSession();<BR>Transaction tx = session.beginTransaction();</FONT></P>
<P><FONT size=2>String hqlDelete = "delete Customer where name = :oldName";<BR>int deletedEntities = s.createQuery( hqlDelete )<BR>.setString( "oldName", oldName )<BR>.executeUpdate();<BR>tx.commit();<BR>session.close();</FONT><BR><BR><A name=116></A>1.1.6 createSQLQuery()<BR><BR>在Hibernate3.0中，Session接口的createSQLQuery()方法被废弃，被移到org.hibernate.classic.Session接口中。Hibernate3.0采用新的SQLQuery接口来完成相同的功能。<BR><BR><A name=117></A>1.1.7 Lifecycle 和 Validatable 接口<BR><BR>Lifecycle和Validatable 接口被废弃，并且被移到org.hibernate.classic包中。<BR><BR><A name=118></A>1.1.8 Interceptor接口<BR><BR>在Interceptor 接口中加入了两个新的方法。 用户创建的Interceptor实现类在升级的过程中，需要为这两个新方法提供方法体为空的实现。此外，instantiate()方法的参数作了修改，isUnsaved()方法被改名为isTransient()。<BR><BR><A name=119></A>1.1.9 UserType和CompositeUserType接口<BR><BR>在UserType和CompositeUserType接口中都加入了一些新的方法，这两个接口被移到org.hibernate.usertype包中，用户定义的UserType和CompositeUserType实现类必须实现这些新方法。</P>
<P>Hibernate3.0提供了ParameterizedType接口，用于更好的重用用户自定义的类型。</P>
<P><A name=1110></A>1.1.10 FetchMode类<BR><BR>FetchMode.LAZY 和 FetchMode.EAGER被废弃。取而代之的分别为FetchMode.SELECT 和FetchMode.JOIN。<BR><BR><A name=1111></A>1.1.11 PersistentEnum类<BR><BR>PersistentEnum被废弃并删除。已经存在的应用应该采用UserType来处理枚举类型。<BR><BR><A name=1112></A>1.1.12 对Blob 和Clob的支持<BR><BR>Hibernate对Blob和Clob实例进行了包装，使得那些拥有Blob或Clob类型的属性的类的实例可以被游离、序列化或反序列化，以及传递到merge()方法中。<BR><BR><A name=1113></A>1.1.13 Hibernate中供扩展的API的变化<BR><BR>org.hibernate.criterion、 org.hibernate.mapping、 org.hibernate.persister和org.hibernate.collection 包的结构和实现发生了重大的变化。多数基于Hibernate <BR>2.1 的应用不依赖于这些包，因此不会被影响。如果你的应用扩展了这些包中的类，那么必须非常小心的对受影响的程序代码进行升级。<BR><BR><A name=12></A>1.2 元数据的变化<BR><BR><A name=121></A>1.2.1 检索策略<BR><BR>在Hibernate2.1中，lazy属性的默认值为“false”，而在Hibernate3.0中，lazy属性的默认值为“true”。在升级映射文件时，如果原来的映射文件中的有关元素，如&lt;set&gt;、&lt;class&gt;等没有显式设置lazy属性，那么必须把它们都显式的设置为lazy=“true”。如果觉得这种升级方式很麻烦，可以采取另一简单的升级方式：在&lt;hibernate-mapping&gt;元素中设置: default-lazy=“false”。 <BR><BR><A name=122></A>1.2.2 对象标识符的映射<BR><BR>unsaved-value属性是可选的，在多数情况下，Hibernate3.0将把unsaved-value="0" 作为默认值。<BR><BR>在Hibernate3.0中，当使用自然主键和游离对象时，不再强迫实现Interceptor.isUnsaved()方法。 如果没有设置这个方法，当Hibernate3.0无法区分对象的状态时，会查询数据库，来判断这个对象到底是临时对象，还是游离对象。不过，显式的使用Interceptor.isUnsaved()方法会获得更好的性能，因为这可以减少Hibernate直接访问数据库的次数。<BR><BR><A name=123></A>1.2.3 集合映射<BR><BR>&lt;index&gt;元素在某些情况下被&lt;list-index&gt;和&lt;map-key&gt;元素替代。此外，Hibernate3.0用&lt;map-key-many-to-many&gt; 元素来替代原来的&lt;key-many-to-many&gt;.元素，用&lt;composite-map-key&gt;元素来替代原来的&lt;composite-index&gt;元素。<BR><BR><A name=124></A>1.2.4 DTD<BR><BR>对象-关系映射文件中的DTD文档，由原来的：<BR>http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd <BR>改为：<BR>http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd<BR><BR><A name=13></A>1.3 查询语句的变化<BR><BR>Hibernate3.0 采用新的基于ANTLR的HQL/SQL查询翻译器，不过，Hibernate2.1的查询翻译器也依然存在。在Hibernate的配置文件中，hibernate.query.factory_class属性用来选择查询翻译器。例如：<BR>（1）选择Hibernate3.0的查询翻译器：<BR>hibernate.query.factory_class= org.hibernate.hql.ast.ASTQueryTranslatorFactory<BR>（2）选择Hibernate2.1的查询翻译器<BR>hibernate.query.factory_class= org.hibernate.hql.classic.ClassicQueryTranslatorFactory</P>
<P><BR><I>提示：ANTLR是用纯Java语言编写出来的一个编译工具，它可生成Java语言或者是C++的词法和语法分析器，并可产生语法分析树并对该树进行遍历。ANTLR由于是纯Java的，因此可以安装在任意平台上，但是需要JDK的支持。</I></P>
<P>Hibernate开发小组尽力保证Hibernate3.0的查询翻译器能够支持Hibernate2.1的所有查询语句。不过，对于许多已经存在的应用，在升级过程中，也不妨仍然使用Hibernate2.1的查询翻译器。<BR>值得注意的是， Hibernate3.0的查询翻译器存在一个Bug：不支持某些theta-style连结查询方言：如Oracle8i的OracleDialect方言、Sybase11Dialect。解决这一问题的办法有两种：（1）改为使用支持ANSI-style连结查询的方言，如 Oracle9Dialect,（2）如果升级的时候遇到这一问题，那么还是改为使用Hibernate2.1的查询翻译器。<BR><BR><A name=131></A>1.3.1 indices()和elements()函数<BR><BR>在HQL的select子句中废弃了indices()和elements()函数，因为这两个函数的语法很让用户费解，可以用显式的连接查询语句来替代 select elements(...) 。而在HQL的where子句中，仍然可以使用elements()函数。<BR></P></TD></TR></TBODY></TABLE><img src ="http://www.blogjava.net/wadise/aggbug/33114.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2006-03-02 08:55 <a href="http://www.blogjava.net/wadise/archive/2006/03/02/33114.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>isAssignableFrom和instanceof的不同</title><link>http://www.blogjava.net/wadise/archive/2005/12/14/23803.html</link><dc:creator>wadise</dc:creator><author>wadise</author><pubDate>Wed, 14 Dec 2005 04:08:00 GMT</pubDate><guid>http://www.blogjava.net/wadise/archive/2005/12/14/23803.html</guid><description><![CDATA[<P><FONT size=1>下面是JUnit的测试代码(测试能通过)：</P>
<DIV style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><SPAN style="COLOR: #008080">&nbsp;1</SPAN><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top><SPAN style="COLOR: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User&nbsp;user&nbsp;</SPAN><SPAN style="COLOR: #000000">=</SPAN><SPAN style="COLOR: #000000">&nbsp;</SPAN><SPAN style="COLOR: #0000ff">new</SPAN><SPAN style="COLOR: #000000">&nbsp;User();<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;2</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertTrue(user.getClass().isAssignableFrom(User.</SPAN><SPAN style="COLOR: #0000ff">class</SPAN><SPAN style="COLOR: #000000">));<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;3</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertFalse(user.getClass().isAssignableFrom(Actor.</SPAN><SPAN style="COLOR: #0000ff">class</SPAN><SPAN style="COLOR: #000000">));<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;4</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertFalse(user.getClass().isAssignableFrom(IUser.</SPAN><SPAN style="COLOR: #0000ff">class</SPAN><SPAN style="COLOR: #000000">));<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;5</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertFalse(user.getClass().isAssignableFrom(IActor.</SPAN><SPAN style="COLOR: #0000ff">class</SPAN><SPAN style="COLOR: #000000">));<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;6</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;7</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertTrue(user&nbsp;</SPAN><SPAN style="COLOR: #0000ff">instanceof</SPAN><SPAN style="COLOR: #000000">&nbsp;User);<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;8</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertTrue(user&nbsp;</SPAN><SPAN style="COLOR: #0000ff">instanceof</SPAN><SPAN style="COLOR: #000000">&nbsp;Actor);<BR></SPAN><SPAN style="COLOR: #008080">&nbsp;9</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertTrue(user&nbsp;</SPAN><SPAN style="COLOR: #0000ff">instanceof</SPAN><SPAN style="COLOR: #000000">&nbsp;IUser);<BR></SPAN><SPAN style="COLOR: #008080">10</SPAN><SPAN style="COLOR: #000000"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assertTrue(user&nbsp;</SPAN><SPAN style="COLOR: #0000ff">instanceof</SPAN><SPAN style="COLOR: #000000">&nbsp;IActor);</SPAN></DIV></FONT><BR><FONT size=1>类与类之间的层次关系是：<BR>
<DIV style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><IMG src="http://www.blogjava.net/images/OutliningIndicators/None.gif" align=top><SPAN style="COLOR: #000000">User&nbsp;extend&nbsp;Actor&nbsp;</SPAN><SPAN style="COLOR: #0000ff">implements</SPAN><SPAN style="COLOR: #000000">&nbsp;IUser</SPAN></DIV></FONT><BR><FONT size=1>从上面可以看出isAssignableFrom和instanceof的不同之处。</FONT><img src ="http://www.blogjava.net/wadise/aggbug/23803.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/wadise/" target="_blank">wadise</a> 2005-12-14 12:08 <a href="http://www.blogjava.net/wadise/archive/2005/12/14/23803.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>