Solved

Including a static file within <%! %> code

Posted on 2006-10-24
17
211 Views
Last Modified: 2013-11-18
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
Comment
Question by:Joe45930
  • 6
  • 5
  • 3
  • +2
17 Comments
 
LVL 9

Expert Comment

by:owenli27
ID: 17799415
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
 
LVL 10

Expert Comment

by:jaggernat
ID: 17799437
>>>>but not with relation to the webapps directory

what is webapps directory? where is it?
0
 
LVL 8

Expert Comment

by:reach2piyush
ID: 17800871
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
 

Author Comment

by:Joe45930
ID: 17800938
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
 
LVL 8

Expert Comment

by:reach2piyush
ID: 17801165
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
 

Expert Comment

by:Mark40302
ID: 17806820
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
 
LVL 9

Expert Comment

by:owenli27
ID: 17806945
printFile("./includes/createUser.html.inc") should be related to your current calling directory
0
 

Expert Comment

by:Mark40302
ID: 17807139
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 9

Expert Comment

by:owenli27
ID: 17807252
BufferedReader in = new BufferedReader(new FileReader("./includes/createUser.html.inc")); doesn't works?
0
 

Expert Comment

by:Mark40302
ID: 17807824
Sorry, I forgot about that one, but I tried it now and it also doesn't work.
0
 
LVL 9

Expert Comment

by:owenli27
ID: 17807992
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
 

Expert Comment

by:Mark40302
ID: 17808158
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
 
LVL 9

Expert Comment

by:owenli27
ID: 17808204
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
 

Expert Comment

by:Mark40302
ID: 17808586
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
 
LVL 9

Assisted Solution

by:owenli27
owenli27 earned 250 total points
ID: 17808865
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
 
LVL 8

Accepted Solution

by:
reach2piyush earned 250 total points
ID: 17809371
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
 

Author Comment

by:Joe45930
ID: 17814952
Thanks for your comments.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Article by: Matthew
I am a very big proponent of technology compliance standards and strive to meet such criteria in all of my work. That includes my site, which is 100% XHTML 1.0 compliant as determined by the World Wide Web Consortium. https://www.matthewstevenkel…
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now