Miscellaneous JSP Info

This is a repository of random info related to Java Server Pages (JSP).

The Path Variable

For my jsp projects, I often use a relative paths that start at the application root. I use this path when creating hyperlinks, paths to images, files, etc. This code covers the cases where your web app may be deployed as a default app on the app server.
    String Path = request.getContextPath();
    try{
        String host = new java.net.URL(request.getRequestURL().toString()).getHost();
        if (host.contains(".")){
            host = host.substring(0, host.lastIndexOf("."));
            if (host.contains(".")){
                host = host.substring(host.lastIndexOf(".")+1);
            }
        }

        if (host.equalsIgnoreCase(Path.replace("/", ""))){
            Path = "/";
        }

        if (!Path.endsWith("/")) Path+="/";
    }
    catch(Exception e){}

Get Physical Location of a JSP File

Whenever I need to access a physical file in my web app, I do something like this:

    public java.io.File getFile(){
        String relPath = request.getServletPath().replace("/", java.io.File.separator);
        return new java.io.File(application.getRealPath("") + relPath);
    }

Dump File Contents to the JSP Output Stream

Sometimes you need a JSP to serve out a file or image. Here's a quick way to do it using the ServletOutputStream and a javaxt.io.File.

try{

  //Parse Querystring
    javaxt.io.File file = new javaxt.io.File(request.getParameter("filename"));

    
  //Get input stream
    java.io.InputStream inputStream = file.getInputStream();


  //Set Response Headers
    response.setHeader ("Content-Type", file.getContentType());
    response.setHeader ("Content-Length", file.getSize() + "");
    response.setHeader ("Cache-Control", "no-cache");


  //You can force users to download the file instead of viewing it in the jsp page with this line:
    //response.setHeader ("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");


  //Dump inputStream to output
    ServletOutputStream outputStream = response.getOutputStream();
    byte[] b = new byte[1024];
    int x=0;
    while ( (x = inputStream.read(b)) != -1) { 
       outputStream.write(b,0,x);
    }
    
    inputStream.close();
    outputStream.close();

}
catch(Exception e){
    out.print("File not found");
}

Alternatively, you can use NIO Channels to improve performance and eliminate potential bottlenecks:

  //Dump file to servlet output stream
    ServletOutputStream outputStream = response.getOutputStream();
    java.nio.channels.FileChannel inputChannel = file.getInputStream().getChannel();
    java.nio.channels.WritableByteChannel outputChannel = 
             java.nio.channels.Channels.newChannel(outputStream);
    
    inputChannel.transferTo(0, inputChannel.size(), outputChannel);

    inputChannel.close();
    outputChannel.close();
    outputStream.close();