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

📄 aucserv.html

📁 jdbc书
💻 HTML
📖 第 1 页 / 共 4 页
字号:
</PRE>

<A NAME="destroy"></A>
<H3>The destroy Method</H3>

The <CODE>destroy</CODE> method is a lifecycle method implemented by 
servlets that need to save their state between servlet loading
and unloading. For example, the <CODE>destroy</CODE> method would
save the current servlet state, and the next time the servlet is
loaded, that saved state would be retrieved by the <CODE>init</CODE>
method. You should be aware that the <CODE>destroy</CODE> 
method might not be called if the server machine crashes.

<PRE>
public void destroy() {
  saveServletState();
}
</PRE>

<A NAME="service"></A>
<H3>The service Method</H3>

The <CODE>AuctionServlet</CODE> is an HTTP servlet that handles
client requests and generates responses through its <CODE>service</CODE>
method. It accepts as parameters the <CODE>HttpServletRequest</CODE>
and <CODE>HttpServletResponse</CODE> request and response objects. 

<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<CODE>HttpServletRequest</CODE> contains the headers and input streams sent 
from the client to the server.</FONT>

<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<CODE>HttpServletResponse</CODE> is the output stream that is used to send
information from the servlet back to the client.</FONT>
</UL>

The <CODE>service</CODE> method handles standard
HTTP client requests received by way of its <CODE>HttpServletRequest</CODE>
parameter by delegating the request to one of the following methods designed 
to handle that request. The different types of requests are described in 
the <A HREF="#requests">HTTP Requests</A> section. 

<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doGet for GET, conditional GET, and HEAD requests.</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doPost for POST requests.</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doPut for PUT requests.</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doDelete for DELETE requests.</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doOptions for OPTIONS requests.</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">doTrace for TRACE requests.</FONT>
</UL>

The <CODE>AuctionServlet</CODE> program provides its own
<CODE>service</CODE> method implementation that calls one of the
following methods based on the value returned by the call
to <CODE>cmd=request.getParameter("action")</CODE>. These method
implementations match the default implementations provided
in the <CODE>doGet</CODE> and <CODE>doPost</CODE> methods called
by the default <CODE>service</CODE> method, but add some auction
application-specific functionality for looking up Enterprise Beans.  

<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">listAllItems(out)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">listAllNewItems(out)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">listClosingItems(out)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">insertItem(out, request)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">itemDetails(out, request)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">itemBid(out, request)</FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">registerUser(out, request)</FONT>
</UL>

<PRE>
public void service(HttpServletRequest request,
                HttpServletResponse response) 
		throws IOException {

  String cmd;
  response.setContentType("text/html");
  ServletOutputStream out = response.getOutputStream();
  if (ctx == null ) {
    try {
      ctx = getInitialContext();
    }catch (Exception e){
      System.err.println(
                  "failed to contact EJB server"+e);
    }
  }

  cmd=request.getParameter("action");
  if(cmd !=null)  {
    if(cmd.equals("list")) {
      listAllItems(out);
    }else 
    if(cmd.equals("newlist")) {
      listAllNewItems(out);
    }else if(cmd.equals("search")) {
      searchItems(out, request);
    }else if(cmd.equals("close")) {
      listClosingItems(out);
    }else if(cmd.equals("insert")) {
      insertItem(out, request);
    }else if (cmd.equals("details")) {
      itemDetails(out, request );
    }else if (cmd.equals("bid")) {
      itemBid(out, request) ;
    }else if (cmd.equals("register")) {
      registerUser(out, request);
    }
  }else{
    // no command set
    setTitle(out, "error");
  }
  setFooter(out);
  out.flush();
}
</PRE>

<A NAME="requests"></A>
<H3>HTTP Requests</H3>

A request is a message sent from a client program such
as a browser to a server program. The first line of the
request message contains a method that indicates the action 
to perform on the incoming Uniform Resource Locator (URL).
The two commonly used mechanisms for sending information
to the server are <CODE>POST</CODE> and <CODE>GET</CODE>.

<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">GET requests might pass parameters to a URL by appending them
to the URL. <CODE>GET</CODE> requests can be bookmarked and emailed and 
include the information to the URL of the response.</FONT>

<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">POST requests might pass additional data to a URL by
directly sending it to the server separately from the URL.
POST requests cannot be bookmarked or emailed and do not change the
URL of the response.</FONT>
</UL>

PUT requests are the reverse of GET requests. Instead of
reading the page, PUT requests write (or store) the page.

<P>
DELETE requests are for removing web pages.

<P>
OPTIONS requests are for getting information about the
communication options available on the request/response
chain.

<P>
TRACE requests are for testing or diagnostic purposes because
they let the client see what is being received at the other
end of the request chain. 

<A NAME="cookie"></A>
<H3>Using Cookies in servlets</H3>

HTTP cookies are essentially custom HTTP headers that are passed between
a client and a server. Although cookies are not overwhelmingly popular, 
they do enable state to be shared between the two machines. For example, 
when a user logs into a site, a cookie can maintain a reference verifying
the user has passed the password check and can use that reference to
identify that same user on future visits.

<P>
Cookies are normally associated with a server. If you set the domain
to <CODE>.java.sun.com</CODE>, then the cookie is associated with the
domain. If no domain is set, the cookie is only associated with the server
that created the cookie.


<A NAME="set"></A>
<H4>Setting a Cookie</H4>

The Java<FONT SIZE="-2"><SUP>TM</SUP></FONT> Servlet API includes a <CODE>Cookie</CODE> class that you
can use to set or retrieve the cookie from the HTTP header. HTTP cookies 
include a name and value pair. 

<P>
The <CODE>startSession</CODE> method shown here is in the 
<A HREF="./Code/login/LoginServlet.java">LoginServlet</A> program. In 
this method, the name in the name and value pair used to create
the <CODE>Cookie</CODE> is <CODE>JDCAUCTION</CODE>,
and a unique identifier generated by the server is the value.

<PRE>
  protected Session startSession(String theuser, 
		String password,
        	HttpServletResponse response) {
    Session session = null;
    if ( verifyPassword(theuser, password) ) {
    // Create a session
      session = new Session (theuser);
      session.setExpires (sessionTimeout + i
	System.currentTimeMillis());
      sessionCache.put (session);

    // Create a client cookie
      Cookie c = new Cookie("JDCAUCTION", 
       	String.valueOf(session.getId()));
      c.setPath ("/");
      c.setMaxAge (-1);
      c.setDomain (domain);
      response.addCookie (c);
    }
    return session;
  }
</PRE>

<P>
Later versions of the Servlet API include a Session API, to create a
session using the Servlet API in the previous example you can use 
the <CODE>getSession</CODE> method. 
<PRE>
   HttpSession session = new Session (true);
</PRE>

The <CODE>startSession</CODE> method is called by requesting the
login action from a <CODE>POST</CODE> to the <CODE>LoginServlet</CODE>
as follows:

<PRE>
&lt;FORM ACTION="/LoginServlet" METHOD="POST"&gt;
&lt;TABLE&gt;
&lt;INPUT TYPE="HIDDEN" NAME="action" VALUE="login"&gt;
&lt;TR&gt;
&lt;TD&gt;Enter your user id:&lt;/TD&gt;
&lt;TD&gt;&lt;INPUT TYPE="TEXT" SIZE=20 
  NAME="theuser"&gt;&lt;/TD&gt;
&lt;/TR&gt;
&lt;TR&gt;
&lt;TD&gt;Enter your password:&lt;TD&gt;
&lt;TD&gt;&lt;INPUT TYPE="PASSWORD" SIZE=20 
  NAME="password"&gt;&lt;/TD&gt;
&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;INPUT TYPE="SUBMIT" VALUE="Login" NAME="Enter"&gt;
&lt;/FORM&gt;
</PRE>

The cookie is created with an maximum age of -1, which means the
cookie is not stored but remains alive while the browser runs. The
value is set in seconds, although when using values smaller than a few
minutes you need to be careful of machine times being slightly out of
sync.

<P>
The path value can be used to specify that the cookie only applies
to files and directories under the path set on that machine. In this example
the root path <CODE>/</CODE> means the cookie is applicable to all directories.

<P>
The domain value in the example is read from the initialization parameters 
for the servlet. If the domain is <CODE>null</CODE>, the cookie is applied to 
that machines domain only.

<A NAME="retrieve"></A>
<H4>Retrieving a Cookie</H4>

The cookie is retrieved from the HTTP headers with a call to
the <CODE>getCookies</CODE> method on the request:

<PRE>
  Cookie c[] = request.getCookies();
</PRE>

You can later retrieve the name and value pair settings by calling
the <CODE>Cookie.getName</CODE> method to retrieve the name,
and the <CODE>Cookie.getValue</CODE> method to retrieve the value. 

<P>
<CODE>LoginServlet</CODE> has a <CODE>validateSession</CODE> method 
that checks the user's cookies to find a <CODE>JDCAUCTION</CODE>
cookie that was set in this domain:

<PRE>
  private Session validateSession 
                (HttpServletRequest request,
  		HttpServletResponse response) {
    Cookie c[] = request.getCookies();
    Session session = null;
    if( c != null ) {
      Hashtable sessionTable = new Hashtable();
      for (int i=0; i &lt; c.length &amp;&amp; 
             session == null; i++ ) {
        if(c[i].getName().equals("JDCAUCTION")) {
          String key = String.valueOf (c[i].getValue());
          session=sessionCache.get(key);
        }
      }
    }
    return session;
  }
</PRE>
<P>
If you use the Servlet session API then you can use the following method, 
note that the parameter is false to specify the session value is returned
and that a new session is not created.
<PRE>
    HttpSession session = request.getSession(false);
</PRE>

<A NAME="gen"></A>
<H4>Generating Sessions</H4>

The <CODE>LoginServlet.validateSession</CODE> method returns a
<CODE>Session</CODE> object represented by the 
<A HREF="./Code/login/Session.java">Session</A> class. 
The <CODE>Session</CODE> class uses an identifier generated from 
a numeric sequence. This numbered session identifier is the value part of
the name and value pair stored in the cookie. 

<P>
The only way to reference the user name on the server is with this
session identifier, which is stored in a simple memory cache with the
other session IDs. When a user terminates a session, the 
<CODE>LoginServlet</CODE> logout action is called like this:

<PRE>
  http://localhost:7001/LoginServlet?action=logout
</PRE>

The session cache implemented in the 
<A HREF="./Code/login/SessionCache.java">SessionCache.java</A> program
includes a reaper thread to remove sessions older than a preset time. The
preset timeout could be measured in hours or days depending on
how many visitors visit the site. 

<A NAME="prevent"></A>
<H4>Preventing Page Caching</H4>

The <CODE>LoginServlet.setNoCache</CODE> method sets the 
<CODE>Cache-Control</CODE> or <CODE>Pragma</CODE> values 
(depending on which version of the HTTP protocol is being used) in the 
response header to <CODE>no-cache</CODE>. The expiration header <CODE>Expires</CODE> 
is also set to 0, alternatively you can set the time to be the current system
time. Even if the client does not cache the page, there are often 
proxy servers in a corporate network that would. Only pages using Secure Socket
Layer (SSL) are not cached by default.

<PRE>

⌨️ 快捷键说明

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