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();
        String host = new;
        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 getFile(){
        String relPath = request.getServletPath().replace("/",;
        return new"") + 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


  //Parse Querystring file = new"filename"));

  //Get input stream 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 = != -1) { 

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 = 
    inputChannel.transferTo(0, inputChannel.size(), outputChannel);