如何在JSP中隐藏/修改URL?

时间:2015-12-23 06:33:40

标签: jsp

我正在使用以下行在浏览器的新标签页中打开文件

锚标记:

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

rs.getString(2)表示要打开的文件

它正常工作,但问题是它显示文件的完全限定路径(文件存储在哪里)服务器

enter image description here

我想隐藏网址以获得更好的安全性,而我希望只在网址中显示“附加证明”作为字符串

有可能吗,任何想法?

1 个答案:

答案 0 :(得分:1)

这是一个非常简化的解决方案。我的想法是做一个表格帖子而不是简单的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>

普通的旧表单帖子仍然会显示文件路径。为了防止这种情况,在服务器端,您定义了一个资源来读取文件并将其写回响应。一个简单的servlet可以完成这项工作。

的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>

servlet看起来像这样:

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();
        } 
    }
}