Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide / modify URL in JSP?

Tags:

jsp

I am using following line to open a file in new Tab for browser

Anchor tag :

<a id="view" target="_blank" class="btn btn-info btn-xs" href="<%=rs.getString(2)%>>

Where rs.getString(2) represents the file to be opened

It works Correctly , but the problem is it displays the fully qualified path of file , (where the file is stored on) server

enter image description here

I want to hide the URL for better security, rather I want to display in URL only "Attached-Proof" as a String

Is it possible, any idea?

like image 779
user2130649 Avatar asked Dec 23 '15 06:12

user2130649


1 Answers

Here's a very much simplified solution. The idea is to do a form post rather than a simple GET.

<head>
    <script type="text/javascript">
        function openFile(fileName) {
            document.getElementById('filename').value = fileName;
            document.getElementById('viewform').submit(); 
        }
    </script>
</head>
<body>
    <a id="view" class="btn btn-info btn-xs" href="javascript:openFile('<%=rs.getString(2)%>');">click me</a>

    <form id="viewform" action="Attached-Proof" target="_blank" method="post">
        <input type="hidden" name="filename" id="filename" value=""/>
    </form>
</body>

A plain old form post is still going to show the file path. To prevent that, on the server side, you define a resource to read the file and write it back to the response. A simple servlet can do the job.

web.xml:

<servlet>
    <servlet-name>view-file</servlet-name>
    <servlet-class>com.example.ViewFileServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>view-file</servlet-name>
    <url-pattern>/Attached-Proof</url-pattern>
</servlet-mapping>

And the servlet would look something like this:

package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewFileServlet extends HttpServlet
{

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("application/pdf");

        File file = new File(getServletContext().getRealPath(request.getParameter("filename")));

        InputStream is = null;
        try {
            is = new FileInputStream(file);

            byte[] buffer = new byte[1024];

            int count;
            while ((count = is.read(buffer)) > 0)
            {
                response.getOutputStream().write(buffer, 0, count);
            }

        } finally {
            if (is != null) is.close();
        } 
    }
}
like image 184
Tap Avatar answered Sep 20 '22 22:09

Tap