[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 226
  • Last Modified:

Including a static file within <%! %> code

Hello experts,

I am having problems trying to include a partial HTML file with relation to the path of the current JSP file within the <%! %> tags. Here is what I have so far:

<%!
    //copies of references that are used to increase the scope in < % ! tags of the predefined JSP references
    JspWriter outputStream;
    HttpServletResponse servletResponse;
    HttpSession httpSession;
    ServletRequest servletRequest;
%>
<%
    //assign these references so the scope of these instances now reaches the < % ! code
    outputStream = out;
    servletResponse = response;
    httpSession = session;
    servletRequest = request;
%>
<%!
  void sampleMethod() {
    printFile("includes/createUser.html.inc");
  }

    /**
     * Prints a static file to the output.
     */
    void printFile(String filename) throws Exception {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String line;
        while((line = in.readLine()) != null) {
            outputStream.println(line);
        }
        in.close();
    }
%>

When I call "sampleMethod()" it will print out the file, "includes/createUser.html.inc", from the working directory, but not with relation to the webapps directory. Also, the <%@ include %> does not work the way I want it to. Let me know if I missed something or need to clarify.
0
Joe45930
Asked:
Joe45930
  • 6
  • 5
  • 3
  • +2
2 Solutions
 
owenli27Commented:
If you want the target file to be related to the webapps directory, you can try:

void sampleMethod() {
    String path = application.getRealPath("/");
    printFile(path + "/includes/createUser.html.inc");
}
0
 
jaggernatCommented:
>>>>but not with relation to the webapps directory

what is webapps directory? where is it?
0
 
reach2piyushCommented:
May be u can try the following simpler approach
<%
    printFile("includes/createUser.html.inc",out,request);
%>

<%!
    /**
     * Prints a static file to the output.
     */
    void printFile(String filename,JspWriter outputStream,HttpServletRequest servletRequest) throws Exception {
        BufferedReader in = new BufferedReader(new FileReader(servletRequest.getRealPath(filename)+filename));
        String line;
        while((line = in.readLine()) != null) {
            outputStream.println(line);
        }
        in.close();
    }
%>
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Joe45930Author Commented:
reach2piyush, when I try your code I get something like:

E:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\includes\createUser.html.incincludes/createUser.html.inc

Your code gets the file path relative to the ROOT directory, but the file is passed as a relative file and the real directory would actually be:

E:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\DATA Tool\Server\JSP and HTML Server Files\includes/reateUser.html.inc

owenli27, your code also gets the path with reference to the root directory, but my web application is not in the root directory.

jaggernat, you can see where webapps is above.

Any way to get relative paths?
0
 
reach2piyushCommented:
Sorry, it should be servletRequest.getRealPath(filename) instead of servletRequest.getRealPath(filename)+filename

Anyways, you can try:

URL url = this.getClass().getResource("/includes/createUser.html");
String path ="RSRC-NOT-FOUND";
if (url != null)
      path = url.getPath();


This method will return a URL only if it is able to find the resource in the classpath..
0
 
Mark40302Commented:
reach2piyush,

The code in your posting did not work for me since the resource was not in the classpath. The url was null for me and thus the path became RSRC-NOT-FOUND. I tried the code with both "/includes/createUser.html" and "includes/createUser.html" and both didn't work.

Does anyone have any more ideas for getting the relative path?
0
 
owenli27Commented:
printFile("./includes/createUser.html.inc") should be related to your current calling directory
0
 
Mark40302Commented:
owenli27,

I now tried

URL url = this.getClass().getResource("./includes/createUser.html.inc");
String path ="RSRC-NOT-FOUND";
if (url != null)
      path = url.getPath();

but it still resulted in a null object for the url.

When I try the code:

filename = servletRequest.getRealPath(filename);

it results in the filename:

E:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\.\includes\createUser.html.inc

so it also doesn't work.
0
 
owenli27Commented:
BufferedReader in = new BufferedReader(new FileReader("./includes/createUser.html.inc")); doesn't works?
0
 
Mark40302Commented:
Sorry, I forgot about that one, but I tried it now and it also doesn't work.
0
 
owenli27Commented:
your calling JSP is in:
..ROOT\DATA Tool\Server\JSP and HTML Server Files\callingInclude.jsp

and your included file in
..ROOT\DATA Tool\Server\JSP and HTML Server Files\includes\reateUser.html.inc

I didn't see anything wrong with this in callingInclude.jsp.

try {
      BufferedReader in = new BufferedReader(new FileReader("./includes/createUser.html.inc"));
      String line = null;
      while((line = in.readLine()) != null) {
            System.out.println(line);
      }
      in.close();
} catch (IOException e) {
      e.printStackTrace();
}
0
 
Mark40302Commented:
I checked the files a lot of times and they are there and have read permissions.

I wrote this, just to be sure, and it says:
java.io.FileNotFoundException: .\sample.inc (The system cannot find the file specified)

Directory entries:
sample.jsp
sample.inc

Source code of sample.jsp:

<%@ page import="javax.servlet.http.*,javax.servlet.jsp.*,java.io.*,java.sql.*,java.net.*" %>
<%!
    //copies of references that are used to increase the scope in < % ! tags of the predefined JSP references
    JspWriter outputStream;
    HttpServletResponse servletResponse;
    HttpSession httpSession;
    ServletRequest servletRequest;
%>
<%
    //assign these references so the scope of these instances now reaches the < % ! code
    outputStream = out;
    servletResponse = response;
    httpSession = session;
    servletRequest = request;
%>
<%!
  void sampleMethod() {
    try {
    printFile("./sample.inc");
      } catch(Exception ex) { try {outputStream.println(ex.toString());}catch(Exception e) {} }
  }

    /**
     * Prints a static file to the output.
     */
    void printFile(String filename) throws Exception {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String line;
        while((line = in.readLine()) != null) {
            outputStream.println(line);
        }
        in.close();
    }
%>
0
 
owenli27Commented:
Before execute a JSP file,  all of jsp files will be converted to Java file and then compiled to class file.  Meanwhile., class file will be in different folder and location.  Your included file (sample.inc ) must be in same folder as your jsp source file.  It should be in same folder as class files.

For example:
sample.jsp will be converted to sample_jsp.java at first.  Then, .java file will be compiled to sample_jsp.class.
The class files could be in somewhere like:  webapps\ROOT\WEB-INF\classes\org\apache\jsp\index_jsp.class.
Your inlcude files should be related to your final class file, not jsp source code file.
0
 
Mark40302Commented:
I saw the files you were talking about. Does anyone know if there an automatic way to get this directory or get the files in the directory or anything?

I have no problem with putting the files there, but the application I'm making would be distributed to other people, and I don't want them to get confused and stuck during the installation of the web app. I might end up just putting the HTML code in the java source and encoding it so it works in the Java quotes.
0
 
owenli27Commented:
when include a static file in a JSP, it is better to use reference related to context roo rather than related to current JSP directory

-Owen
0
 
reach2piyushCommented:
I agree with what Owen has suggested,

As There will be no direct method to do what you want as the context are different for the JSP code & the generated HTML code, The sample code in your JSP will work when you will provide the complete path to the FileReader

Although you can construct the path by first getting the current file path & manipulating the string by using substring & replacing the current file name & folder with the new one

For getting the current file path, you can use the following
getServletContext().getRealPath(request.getServletPath());
0
 
Joe45930Author Commented:
Thanks for your comments.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 5
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now