I created a JSP Tag Handler class in Java and defined it in XML in the .tld file.
In my .jsp file, I declared the tag and defined its attributes – one of them being the path to the file that is to be read.
When passing the virtual path to the ServletContext’s getRealPath method, it returns this weird, non-existent file path. When I tried to just simply pass the real file path outright to the tag, it gives me some weird “access denied” message.
What makes this more confusing to me, is that I managed to accomplish the same thing without tags but having the HttpServlet handle the work all by itself. The HttpServlet has no problems with carrying out this task, but the jsp tag class can’t and I don’t know why.
Can someone with any experience in IO tasks and writing custom java tags help me on this one?
Update:
Here’s what the file directory of my website looks like (where “..” represents that there are additional files and folders within that directory that aren’t shown). Also note, that using “<” and “>” causes the text to disappear on this forum, so I couldn’t use them to specify a general label for the directory but that whatever is in all caps isn’t actually the name of the directory:
ROOT/Accounts/.. (location of
Login.jsp)ROOT/data/.. (location of
datafile to be read)ROOT/.. (other
folders)
Since, the project is named “Epsilon” in Eclipse, the resulting URL for any one of these directories is:
http://localhost:8080/Epsilon/Accounts/..
In the jsp file, I define it as follows:
<tags:HeaderContent path="/data/header.markup" id="topMenu"></tags:HeaderContent>
*Note the attribute “path”, because it’s really important!
In the Java class, in the doStartTag() method, I have the following:
ServletContext context = pageContext.getServletContext();
JspWriter out = pageContext.getOut();
String realPath = context.getRealPath(context.getContextPath()
+ path);
out.println(getHeaderContent(realPath).toString());
The context.getContextPath() and the path variables both end up being
“/Epsilon/data/header.markup”.
I pass those two concatenated strings as arguments for the ServletContext object’s getRealPath method. What the realPath String results in is the following:
“Z:\Dropbox\workspaces\Sites.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Epsilon\Epsilon\data\header.markup”
I really don’t know why it returned the metadata folder, but this is not where the file is actually located. And, as I already mentioned earlier, the HttpServlet didn’t encounter this same problem but the JSP tag’s class did.
You should not include the context path in the
getRealPath()call. The context path is only represented in URLs and not in the local disk file system. ThegetRealPath()expects a relative local disk file system path relative to the webcontent root.As to why it’s located in Eclipse’s metadata folder, that’s just because you deployed and run this from inside Eclipse. This should not harm, this is exactly what the
getRealPath()should be taking care of.