📄 defaultservlet.java
字号:
// Render the directory entries within this directory
DirContext directory = resourceInfo.directory;
NamingEnumeration enum =
resourceInfo.resources.list(resourceInfo.path);
boolean shade = false;
while (enum.hasMoreElements()) {
NameClassPair ncPair = (NameClassPair) enum.nextElement();
String resourceName = ncPair.getName();
ResourceInfo childResourceInfo =
new ResourceInfo(resourceName, directory);
String trimmed = resourceName/*.substring(trim)*/;
if (trimmed.equalsIgnoreCase("WEB-INF") ||
trimmed.equalsIgnoreCase("META-INF"))
continue;
sb.append("<tr");
if (shade)
sb.append(" bgcolor=\"#eeeeee\"");
sb.append(">\r\n");
shade = !shade;
sb.append("<td align=\"left\"> \r\n");
sb.append("<a href=\"");
sb.append(rewriteUrl(contextPath));
resourceName = rewriteUrl(name + resourceName);
sb.append(resourceName);
if (childResourceInfo.collection)
sb.append("/");
sb.append("\"><tt>");
sb.append(trimmed);
if (childResourceInfo.collection)
sb.append("/");
sb.append("</tt></a></td>\r\n");
sb.append("<td align=\"right\"><tt>");
if (childResourceInfo.collection)
sb.append(" ");
else
sb.append(renderSize(childResourceInfo.length));
sb.append("</tt></td>\r\n");
sb.append("<td align=\"right\"><tt>");
sb.append(childResourceInfo.httpDate);
sb.append("</tt></td>\r\n");
sb.append("</tr>\r\n");
}
} catch (NamingException e) {
// Something went wrong
e.printStackTrace();
}
// Render the page footer
sb.append("</table>\r\n");
sb.append("<HR size=\"1\" noshade>");
String readme = getReadme(resourceInfo.directory);
if (readme!=null) {
sb.append(readme);
sb.append("<HR size=\"1\" noshade>");
}
sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
sb.append("</body>\r\n");
sb.append("</html>\r\n");
// Return an input stream to the underlying bytes
writer.write(sb.toString());
writer.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
}
/**
* Render the specified file size (in bytes).
*
* @param size File size (in bytes)
*/
protected String renderSize(long size) {
long leftSide = size / 1024;
long rightSide = (size % 1024) / 103; // Makes 1 digit
if ((leftSide == 0) && (rightSide == 0) && (size > 0))
rightSide = 1;
return ("" + leftSide + "." + rightSide + " kb");
}
/**
* Get the readme file as a string.
*/
protected String getReadme(DirContext directory) {
if (readmeFile!=null) {
try {
Object obj = directory.lookup(readmeFile);
if (obj!=null && obj instanceof Resource) {
StringWriter buffer = new StringWriter();
InputStream is = ((Resource)obj).streamContent();
copyRange(new InputStreamReader(is),
new PrintWriter(buffer));
return buffer.toString();
}
} catch(Throwable e) {
; /* Should only be IOException or NamingException
* can be ignored
*/
}
}
return null;
}
/**
* Return the xsl template inputstream (if possible)
*/
protected InputStream findXsltInputStream(DirContext directory) {
if (localXsltFile!=null) {
try {
Object obj = directory.lookup(localXsltFile);
if (obj!=null && obj instanceof Resource) {
InputStream is = ((Resource)obj).streamContent();
if (is!=null)
return is;
}
} catch(Throwable e) {
; /* Should only be IOException or NamingException
* can be ignored
*/
}
}
/* Open and read in file in one fell swoop to reduce chance
* chance of leaving handle open.
*/
if (globalXsltFile!=null) {
FileInputStream fis = null;
try {
File f = new File(globalXsltFile);
if (f.exists()){
fis =new FileInputStream(f);
byte b[] = new byte[(int)f.length()]; /* danger! */
fis.read(b);
return new ByteArrayInputStream(b);
}
} catch(Throwable e) {
log("This shouldn't happen (?)...", e);
return null;
} finally {
try {
if (fis!=null)
fis.close();
} catch(Throwable e){
;
}
}
}
return null;
}
// -------------------------------------------------------- Private Methods
/**
* Check if the if-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
private boolean checkIfMatch(HttpServletRequest request,
HttpServletResponse response,
ResourceInfo resourceInfo)
throws IOException {
String eTag = getETag(resourceInfo);
String headerValue = request.getHeader("If-Match");
if (headerValue != null) {
if (headerValue.indexOf('*') == -1) {
StringTokenizer commaTokenizer = new StringTokenizer
(headerValue, ",");
boolean conditionSatisfied = false;
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
// If none of the given ETags match, 412 Precodition failed is
// sent back
if (!conditionSatisfied) {
response.sendError
(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/**
* Check if the if-modified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
private boolean checkIfModifiedSince(HttpServletRequest request,
HttpServletResponse response,
ResourceInfo resourceInfo)
throws IOException {
try {
long headerValue = request.getDateHeader("If-Modified-Since");
long lastModified = resourceInfo.date;
if (headerValue != -1) {
// If an If-None-Match header has been specified, if modified since
// is ignored.
if ((request.getHeader("If-None-Match") == null)
&& (lastModified <= headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return false;
}
}
} catch(IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Check if the if-none-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
private boolean checkIfNoneMatch(HttpServletRequest request,
HttpServletResponse response,
ResourceInfo resourceInfo)
throws IOException {
String eTag = getETag(resourceInfo);
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!headerValue.equals("*")) {
StringTokenizer commaTokenizer =
new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
// For GET and HEAD, we should respond with
// 304 Not Modified.
// For every other method, 412 Precondition Failed is sent
// back.
if ( ("GET".equals(request.getMethod()))
|| ("HEAD".equals(request.getMethod())) ) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return false;
} else {
response.sendError
(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/**
* Check if the if-unmodified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceInfo File object
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
private boolean checkIfUnmodifiedSince(HttpServletRequest request,
HttpServletResponse response,
ResourceInfo resourceInfo)
throws IOException {
try {
long lastModified = resourceInfo.date;
long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if ( lastModified > headerValue ) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch(IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
*
* @exception IOException if an input/output error occurs
*/
private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream)
throws IOException {
IOException exception = null;
// Optimization: If the binary content has already been loaded, send
// it directly
if (resourceInfo.file != null) {
byte buffer[] = resourceInfo.file.getContent();
if (buffer != null) {
ostream.write(buffer, 0, buffer.length);
return;
}
}
InputStream resourceInputStream = resourceInfo.getStream();
InputStream istream = new BufferedInputStream
(resourceInputStream, input);
// Copy the input stream to the output stream
exception = copyRange(istream, ostream);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -