⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webapp-overview.xtp

📁 RESIN 3.2 最新源码
💻 XTP
📖 第 1 页 / 共 4 页
字号:
<example>&lt;%@page session="true"&gt;</example><p>The default for <code>session</code> is <var>true</var>, which isconvenient for pages that need the session, but creates an undue burden on theserver if the page does not need the session.  Therefore it is best to mark allJSP pages with <code>session="false"</code> unless they really do need thesession.</p><example>&lt;%@page session="false"&gt;</example></s3></s2> <!-- obtain-jsp --></s1> <!-- obtain --><s1 name="attributes" title="Attributes"><p>Each of the objects <code>application</code>, <code>session</code>, and<code>request</code> can have <var>attributes</var>. These attributes consistof a <var>name</var> and a <var>value</var>.</p><p>Using attributes the developer can store a value for later retrieval.</p><p>The <var>name</var> is a String that uniquely identifies the attribute, and the<var>value</var> is a Java object.</p><s2 title="The API for setting and getting attributes"><p>The following methods are available for the <code>application</code>,<code>session</code>, and <code>request</code> objects.</p><deftable title="API for attributes"><tr><th>Method</th><th>Description</th></tr><tr><td>getAttribute(String name)</td><td>Return the <code>Object</code> that is associated with the passed<var>name</var>.  Usually you will need to cast the Object to whateverclass you know it to be.  If there is no attribute with the given name,<code>null</code> is returned.</td></tr><tr><td>setAttribute(String name, Object value)</td><td>Associates the given <var>name</var> with the <var>value</var>. If anattribute <code>name</code> already exists, it is replaced.</td></tr><tr><td>removeAttribute(String name)</td><td>Removes the attribute with the given <var>name</var> if it exists.</td></tr></deftable></s2><s2 title="Choosing where to put attributes"><p>As a developer you have a choice of which object to store attributesin. The object that you choose should be appropriate to the scopewithin which you will need to get that value out again.</p><p>Whenever possible put the attribute in the request object. If thatcannot work, put it in the session object. And very rarely, put valuesin the application object.  </p><p>The reason for this order is simple, all of the attributes in asession cannot be garbage collected until they are explicitly removedor the session expires. All of the objects in the application stayuntil they are explicitly removed or the web application is stopped orrestarted.</p></s2></s1> <!-- attributes --><s1 name="use-response" title="Using the Response object"><s2 title="Encoding the URL"><p>Probably the most important and most frequent usage of the responseobject is to rewrite the URL. Recall from earlier that in order tomaintain the identity of a Session with the user Resin mayhave to add a special parameter to every URL. The developer mustco-operate with this, using the <a href="javadoc|javax.servlet.http.HttpServletResponse|encodeURL(String)">response.encodeURL</a> method.</p><p>Because of this, it is a good idea to form a String for every URL youwill use in a page and store it in a variable:</p><example title="EncodingUrls.jsp - Encoding the URL's and storing them in a String variable">&lt;%    String boatUrl = response.encodeURL("water/boat.jsp");    String goatUrl = response.encodeURL("animals/goat.jsp");%&gt;&lt;%-- the presentation --%&gt;Hello, would you like some green eggs and ham?Would you, could you, on a &lt;a href='&lt;%= boatUrl %&gt;'&gt;boat&lt;/a&gt;?Would you, could you, with a&lt;a href='&lt;%= goatUrl %&gt;'&gt;goat&lt;/a&gt;?</example><p>This has the added benefit of placing all of your URL's inone place, allowing you to change them more easily.</p></s2><s2 name="redirect" title="Redirecting the users browser"><p>Sometimes it is desirable to send a redirect to the client. This is aresponse to the client that tells it to go to some other URL. This isoften used by developers so that the URL in the browser makes sense tothe user. It is however, a slow procedure because it requires aresponse to go all the way back to the browser, and then the browserwill make a new request.</p><p>The redirect is accomplished by using the <code>response.sendRedirect()</code>method. Again, the URL must be encoded, and a special kind of encodingis needed for a redirect:</p><example title="Redirect.jsp - an example of redirecting the client">&lt;%    String redirectUrl =      response.encodeRedirectURL("elsewhere.jsp");   response.sendRedirect(redirectUrl);%&gt;</example><s3 title="A note on redirecting wireless devices"><p>Redirects often do not work with wireless devices like cell phones and WMLclients, and the emulators of these devices. As well, the latency of a wirelessconnection compounds the speed problem of using redirects.  Redirects shouldprobably be avoided with wireless devices.</p></s3></s2> <!-- redirect --><s2 title="Setting the content type dynamically"><p>As mentioned eariler, the <code>&lt;%@ page contentType="..." %&gt;</code>directive can be used to tell the browser the type of content that it isgetting.</p><p>The page directive method does not allow you to do thisdynamically. You can instead use: <code>response.setContentType("...")</code>to set the content type.</p></s2><s2 title="Telling the browser not to cache the page"><p>Often it is necessary to inform the browser that a page should not becached - the browser should ask for a new copy of the page everytime. The best way to do this is by setting appropriate HTTP headersin the response to the browser.</p><p>Unfortunately, all the browsers work differently.  The following seemsto be a consensus on the headers to set:</p><example title="nocache.jsp - Stop the browser from caching the page">&lt;%/** stop browser from caching */response.setHeader("Cache-Control","no-cache,post-check=0,pre-check=0,no-cache");response.setHeader("Pragma","no-cache");response.setHeader("Expires","Thu,01Dec199416:00:00GMT");%&gt;</example></s2><s2 title="Telling the browser that the page is private"><p>A little known fact is that it is necessary to inform the browser withcertain pages that they are private pages, meaning they should neverbe seen by anyone except the current user.</p><p>This applies to any pages that the user has needed a password to get to.</p><example title="private.jsp - Telling the browser the page is private">&lt;%/** * Add an HTTP header to the response that  * indicates to the browser and any * intervening cache's that this is a private  * page, and should never be seen * by a different user. */response.addHeader("Cache-Control","private");%&gt;</example></s2></s1> <!-- use-response --><s1 name="use-request" title="Using the Request object"><s2 title="Retrieving the values set in form fields"><p>The main use of the request object is to get the values that a userhas supplied in a form submit. For example, with this HTML onpage a.jsp:</p><example title="a.jsp - a form that submits a value">&lt;%     String bUrl = response.encodeUrl("b.jsp");%&gt;&lt;%-- presentation --%&gt;&lt;form method="post" action="&lt;%= bUrl %&gt;"&gt;What is your favourite kind of eggs?&lt;input type="text" name="favegss" size="25"&gt;&lt;br&gt;&lt;input type="submit" value="Submit"&gt;&lt;input type="reset" value="Reset"&gt;&lt;/form&gt;</example><p>The value that was supplied in ``eggs'' can be retrieved with:</p><example title="b.jsp - retrieving a value from a form submit">&lt;%     String aUrl = response.encodeUrl("a.jsp");%&gt;&lt;%     String faveggs = request.getParameter("eggs");     if ((faveggs != null) &amp;&amp; (faveggs.trim().length() == 0))        faveggs = null;%&gt;&lt;%-- presentation --%&gt;&lt;% if (faveggs == null) { %&gt;No eggs supplied!&lt;a href="&lt;%= aUrl %&gt;"&gt;Try again&lt;/a&gt;&lt;% } else if (faveggs.equals("green"))  { %&gt;Of course we have &lt;%= faveggs %&gt; eggs! It's one of our favourites too.&lt;% } else { %&gt;We do not have &lt;%= faveggs %&gt; eggs.&lt;% } %&gt;</example></s2></s1> <!-- use-request --><s1 name="use-session" title="Using the Session object"><p>The Session object is used primarily to store two types ofinformation. The first is information about the user, and the secondis data that is built up and used over multiple pages.  A classicexample of information you would store in a session is user profileinformation, or a shopping cart that is filled up over many pages.</p><p>It is important to try to limit the amount of information that isstored in the session object.</p><s2 title="Explicitly causing the session to end"><p>The session object will go away if the user is inactive for a certaintime (usually 1/2 hour). You can also explicitly destroy the session,which you may want to do for example if the user chooses to logout.</p><p>This is accomplished with: <code>session.invalidate();</code></p></s2><s2 title="Doing something when the Session goes away"><p>It is possible to add a hook so that something can be done whenResin decides that a Session has expired, or the Session isexplicitly destroyed.</p><p>To accomplish this, you write a class that implements the<a href="javadoc|javax.servlet.http.HttpSessionBindingListener"/> interface.Then you register this class with the session simply by putting it as one ofthe attributes. The Session will notify all of it's attributes that implement <a href="javadoc|javax.servlet.http.HttpSessionBindingListener"/>.</p><example title="SessionBind.jsp - An example of getting notification when a Session is destroyed">&lt;%@page import="example.SessionListener" %&gt;&lt;%    // example.SessionListener implements HttpSessionBindingListener     SessionListener d = new SessionListener();    session.setAttribute("sessiongoesbyebye", d);%&gt;</example></s2><s2 title="Warning! One session does not mean one browser window!"><p>It is important to realize that the user can have multiplewindows open that use the same session. If the user uses the "Open innew Window" functionality of a browser, they will have two windowsopen and the Web Application will see them both as belonging to thesame session. This has some ramifications on how the Session can beused for shopping-cart like applications.</p><p>For example, let's assume that an application uses the Sessionattribute "cart" to store shopping cart information about differenttypes of juice a user has chosen to purchase. </p><p>The user may start one juice buying transaction and get to theconfirmation page, having 3 grape and 2 apple in theircart. Now, what happens if at this point they use another browserwindow to initiate another purchase? If the Web Application is usingthe Session to store shopping cart information then the second windowmay destroy the contents of the shopping cart, so that if the userfinishes the first window they end up buying nothing!</p><p>A possible solution for this is to keep a <var>version counter</var> in yourcart.  Every time the cart is changed, the version counter is updated.Then, when your application shows the "confirm purchase" page (the next actionwill cause the purchase to occur), it sends the version counter to the "confirmpurchase page".  The "confirm purchase" page submits that version counter as aparameter.  The application can check the submitted version counter, and thecurrent version counter in the shopping cart - if they are different then thecart has been modified in some other way, and a message is returned that thepurchase did not occur because the cart had been modified elsewhere.</p></s2></s1> <!-- use-session --><s1 name="errors" title="Error Handling"><s2 title="JSP Translation Time Processing Errors"><p>Some errors may occur at JSP translation time.  This could be, forexample, from an error in the syntax of some Java code in your JSP.You will usually see this error in your browser the first time you tryto access the page.  Resin can also put the error in log files.</p><p>From the JSP specification:</p><blockquote>The translation of a JSP page source into a corresponding JSP pageimplementation class using the Java technology by a JSP container canoccur at any time between initial deployment of the JSP page into theruntime environment of a JSP container, and the receipt and processingof a client request for the target JSP page. If translation occursprior to the JSP container receiving a client request for the target(untranslated) JSP page then error processing and notification isimplementation dependent. Fatal translation failures shall result insubsequent client requests for the translation target to also befailed with the appropriate error; for HTTP protocols, error statuscode 500 (Server Error).</blockquote></s2><s2 title="Coompilation Time Processing Errors"><p>Some errors may occur at the time a Servlet or other source file is beingcompiled by Resin. This could be, for example, from an error in the syntax ofthe Java code.You will usually see this error in your browser the first time you tryto access the page.  Resin might also put the error in log files.</p></s2><s2 title="Client Request Time Processing Errors"><p>Java handles runtime errors with exceptions.  If an exception is notcaught in your JSP or Servlet, Resin will use a special error pageto send results back to the browser.  Resin uses a default errorpage unless you explicitly provide an error page yourself.</p><p>From the JSP specification:</p><blockquote><p>During the processing of client requests, arbitrary runtime errors canoccur in either the body of the JSP page implementation class or insome other code (Java or other implementation programming language)called from the body of the JSP page implementation class. Such errorsare realized in the page implementation using the Java programminglanguage exception mechanism to signal their occurrence to caller(s)of the offending behavior 1 .  These exceptions may be caught andhandled (as appropriate) in the body of the JSP page implementationclass.</p><p>However, any uncaught exceptions thrown from the body of the JSP pageimplementation class result in the forwarding of the client requestand uncaught exception to the errorPage URL specified by the offendingJSP page (or the implementation default behavior, if none isspecified).</p>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -