📄 aucserv.html
字号:
private void setNoCache (HttpServletRequest request,
HttpServletResponse response) {
if(request.getProtocol().compareTo ("HTTP/1.0") == 0) {
response.setHeader ("Pragma", "no-cache");
} else if (request.getProtocol().compareTo
("HTTP/1.1") == 0) {
response.setHeader ("Cache-Control", "no-cache");
}
response.setDateHeader ("Expires", 0);
}
</PRE>
<A NAME="use"></A>
<H4>Restricting Access and Redirections</H4>
If you install the <CODE>LoginServlet</CODE> as the default servlet or
servlet to run when serving any page under the document root, you can
use cookies to restrict users to certain sections of the site. For
example, you can allow users who have cookies that state they
have logged in to access sections of the site that require
a login password and keep all others out.
<P>
The <A HREF="./Code/login/LoginServlet.java">LoginServlet</A> program checks
for a restricted directory in its <CODE>init</CODE> method. The <CODE>init</CODE>
method shown below sets the <CODE>protectedDir</CODE> variable to <CODE>true</CODE>
if the <CODE>config</CODE> variable passed to it specifies a protected directory.
The web server configuration file provides the settings passed to a servlet
in the <CODE>config</CODE> variable.
<PRE>
public void init(ServletConfig config)
throws ServletException {
super.init(config);
domain = config.getInitParameter("domain");
restricted = config.getInitParameter("restricted");
if(restricted != null) {
protectedDir=true;
}
</PRE>
Later on in the <CODE>validateSession</CODE> and <CODE>service</CODE>
methods, the <CODE>protectedDir</CODE> variable is checked and the
<CODE>HttpResponse.sendRedirect</CODE> method is called to send
the user to the correct page based on their login and session status.
<PRE>
if(protectedDir) {
response.sendRedirect (restricted+"/index.html");
}else{
response.sendRedirect (defaultPage);
}
</PRE>
<P>
The <CODE>init</CODE> method also retrieves the servlet context for
the <CODE>FileServlet</CODE> servlet so methods can be called on
the <CODE>FileServlet</CODE> in the <CODE>validateSession</CODE>
method. The advantage to calling methods on the <CODE>FileServlet</CODE>
servlet to serve the files rather than serving the files from
within the <CODE>LoginServlet</CODE> servlet, is you get the
full advantage of all the functionality added into the <CODE>FileServlet</CODE>
servlet such as memory mapping or file caching.
The downside is that the code may not be portable to other servers that
do not have a <CODE>FileServlet</CODE> servlet.
This code retrieves the <CODE>FileServlet</CODE> context.
<P>
<PRE>
FileServlet fileServlet=(FileServlet)
config.getServletContext().getServlet("file");
</PRE>
The <CODE>validateSession</CODE> method prevents users without a
logon session from accessing the restricted directory.
<A NAME="error"></A>
<H3>HTTP Error Codes</H3>
You can return a HTTP error code using the <CODE>sendError</CODE>
method. For example, the HTTP 500 error code indicates an internal
server error, and the 404 error code indicates page not found.
This code segment returns the HTTP 500 error code.
<PRE>
protected void service (HttpServletRequest request,
HttpServletResponse response)
throws ServletException {
response.sendError (500);
}
</PRE>
<A NAME="getpost"></A>
<H3>Reading GET and POST Values</H3>
The Servlet API has a <CODE>getParameter</CODE> method in the
<CODE>HttpServletRequest</CODE> class that returns the <CODE>GET</CODE> or
<CODE>POST</CODE> value for the name you supply.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">The HTTP <CODE>GET</CODE> request handles name and value pairs
as part of the URL. The <CODE>getParameter</CODE> method parses
the URL passed in, retrieves the <CODE>name=value</CODE> pairs
deliminated by the ampersand (<CODE>&</CODE>) character, and returns
the value. </FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">The HTTP <CODE>POST</CODE> request reads the name and value pairs
from the input stream from the client. The <CODE>getParameter</CODE>
method parses the input stream for the name and value pairs. </FONT>
</UL>
<P>
The <CODE>getParameter</CODE> method works well for simple servlets,
but if you need to retrieve the <CODE>POST</CODE> parameters in the
order they were placed on the web page or handle multi-part posts, you
can write your own code to parse the input stream.
<P>
The next example returns POST parameters in the order they
were received from the web page. Normally, the parameters are
stored in a <CODE>Hashtable</CODE> which does not maintain the sequence
order of elements stored in it. The example keeps a reference to
each name and value pair in a vector that can be traversed to
return the values in the order they were received by the server.
<PRE>
package auction;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostServlet extends HttpServlet {
private Vector paramOrder;
private Hashtable parameters;
public void init(ServletConfig config)
throws ServletException {
super.init(config);
}
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if(request.getMethod().equals("POST")
&& request.getContentType().equals(
"application/x-www-form-urlencoded")) {
parameters=parsePostData(
request.getContentLength(),
request.getInputStream());
}
for(int i=0;i<paramOrder.size();i++) {
String name=(String)paramOrder.elementAt(i);
String value=getParameter((
String)paramOrder.elementAt(i));
out.println("name="+name+" value="+value);
}
out.println("</body></html>");
out.close();
}
private Hashtable parsePostData(int length,
ServletInputStream instream) {
String valArray[] = null;
int inputLen, offset;
byte[] postedBytes = null;
boolean dataRemaining=true;
String postedBody;
Hashtable ht = new Hashtable();
paramOrder= new Vector(10);
StringBuffer sb = new StringBuffer();
if (length <=0) {
return null;
}
postedBytes = new byte[length];
try {
offset = 0;
while(dataRemaining) {
inputLen = instream.read (postedBytes,
offset,
length - offset);
if (inputLen <= 0) {
throw new IOException ("read error");
}
offset += inputLen;
if((length-offset) ==0) {
dataRemaining=false;
}
}
} catch (IOException e) {
System.out.println("Exception ="+e);
return null;
}
postedBody = new String (postedBytes);
StringTokenizer st =
new StringTokenizer(postedBody, "&");
String key=null;
String val=null;
while (st.hasMoreTokens()) {
String pair = (String)st.nextToken();
int pos = pair.indexOf('=');
if (pos == -1) {
throw new IllegalArgumentException();
}
try {
key = java.net.URLDecoder.decode(
pair.substring(0, pos));
val = java.net.URLDecoder.decode(
pair.substring(pos+1,
pair.length()));
} catch (Exception e) {
throw new IllegalArgumentException();
}
if (ht.containsKey(key)) {
String oldVals[] = (String []) ht.get(key);
valArray = new String[oldVals.length + 1];
for (int i = 0; i < oldVals.length; i++) {
valArray[i] = oldVals[i];
}
valArray[oldVals.length] = val;
} else {
valArray = new String[1];
valArray[0] = val;
}
ht.put(key, valArray);
paramOrder.addElement(key);
}
return ht;
}
public String getParameter(String name) {
String vals[] = (String []) parameters.get(name);
if (vals == null) {
return null;
}
String vallist = vals[0];
for (int i = 1; i < vals.length; i++) {
vallist = vallist + "," + vals[i];
}
return vallist;
}
}
</PRE>
To find out whether the request is POST or GET, call the
<CODE>getMethod</CODE> in the <CODE>HttpServletRequest</CODE> class.
To determine the format of the data being posted, call the
<CODE>getContentType</CODE> method in the <CODE>HttpServletRequest</CODE>
class. For simple HTML web pages, the type returned by this call
will be <CODE>application/x-www-form-urlencoded</CODE>.
<P>
If you need to create a post with more than one part such
as the one created by the following HTML form, the servlet
will need to read the input stream from the post to
reach individual section. Each section distinguished by a
boundary defined in the post header.
<PRE>
<FORM ACTION="/PostMultiServlet"
METHOD="POST" ENCTYPE="multipart/form-data">
<INPUT TYPE="TEXT" NAME="desc" value="">
<INPUT TYPE="FILE" NAME="filecontents" value="">
<INPUT TYPE="SUBMIT" VALUE="Submit" NAME="Submit">
</FORM>
</PRE>
The next example extracts a description and a file from the client
browsers. It reads the input stream looking for a line matching the
boundary string, reads the content line, skips a line and then reads
the data associated with that part. The uploaded file is simply displayed,
but could also be written to disk.
<PRE>
package auction;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostMultiServlet extends HttpServlet {
public void init(ServletConfig config)
throws ServletException {
super.init(config);
}
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (request.getMethod().equals("POST")
&& request.getContentType().startsWith(
"multipart/form-data")) {
int index = request.getContentType().indexOf(
"boundary=");
if (index < 0) {
System.out.println("can't find boundary type");
return;
}
String boundary =
request.getContentType().substring(
index+9);
ServletInputStream instream =
request.getInputStream();
byte[] tmpbuffer = new byte[8192];
int length=0;
String inputLine=null;
boolean moreData=true;
//Skip until form data is reached
length = instream.readLine(
tmpbuffer,
0,
tmpbuffer.length);
inputLine = new String (tmpbuffer, 0, 0,
length);
while(inputLine.indexOf(boundary)
>0 && moreData) {
length = instream.readLine(
tmpbuffer,
0,
tmpbuffer.length);
inputLine = new String (tmpbuffer, 0, 0,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -