Java Reference
In-Depth Information
String e = (String) tok.nextElement();
if (!e.trim().equalsIgnoreCase(File.separator))
{
As the elements of the file are parsed, the program must look out for the previous direc-
tory code of “..”. If “..” is allowed to be part of the path, a malicious user could use “..” to ac-
cess the parent HTTP root directory. This would be a security risk. Therefore, if the string
“..” is located inside of the URL, an error is displayed.
if (e.equals("..") || e.equals("."))
{
error(out, 500, "Invalid request");
return;
}
For each section, the sub directory, or file, is concatenated to the physicalPath
variable. Additionally, a slash is added for each of the sub directory levels.
physicalPath += e;
} else
physicalPath = addSlash(physicalPath);
}
Now, that the entire path has been parsed, it is time to check for a default file. If the path
specified by the user is a directory only, the default file index.html needs to be specified
as shown below:
// If there is no file specified, default
// to index.html.
if (physicalPath.endsWith(File.separator))
physicalPath = physicalPath + "index.html";
Once the path is complete, there are really only two possibilities that will occur. Either
the file will be transmitted to the user or a 404 error will be generated. The error code 404 ,
which is the most famous of HTTP error codes, means that the file was not found.
Next the file that is to be transmitted must be read. The following lines of code will read
the file.
// Open the file and send it if it exists.
File file = new File(physicalPath);
if (file.exists())
{
// Send the file.
FileInputStream fis = new FileInputStream(file);
byte buffer[] = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
Search WWH ::




Custom Search