How to hide / change url in JSP?

I use the following line to open the file in a new tab for the 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 open

It works correctly, but the problem is that it displays the full path to the file, (where the file is stored on the server)

enter image description here

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

Is any idea possible?

+6
source share
1 answer

Here is a very simplified solution. The idea is to make a form message, not just a 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 simple old form entry will still show the file path. To prevent this, 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 will 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(); } } } 
+1
source

All Articles