如何在 jsp 中显示多个 Pdf

How to display multiple Pdfs in jsp

我在 jsp 中有一个包含用户信息的 table,其中一列代表用户 CV:

名字 - 姓氏 - 简历

Tom-bla-file:///C:/CVs/Tombla.pdf

Jon-b-file:///C:/CVs/jonb.pdf

但是,两个用户最终都显示了相同的 pdf。

我正在尝试使用以下页面中的代码:

[link] Displaying pdf in jsp


<table id="users" class="display" style="width:100%;">
<thead>
  <tr>
    <th>First Name</th>
    <th>Last name</th>
    <th>Cv</th>
  </tr>
 </thead>
 <tbody>
 <%
    List<User> users= findUsers();

   for(User user: users) {
 %>
<tr>
 <td><%= user.firstName() %></td>
 <td><%= user.lastName() %></td>
 <td>
   <object data="${pageContext.request.contextPath}/cv.pdf" type="application/pdf"/><% session.setAttribute("cv", user.getCV()); %>                             
 </td>
</tr>
<% 
} 
%>
</tbody>
</table>

```Webservlet

@WebServlet("/cv.pdf")
public class Cv extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    String cv = session.getAttribute("cv").toString() + ".pdf";

    File file = new File(cv );
    response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "inline; filename=\"cv.pdf\"");
    Files.copy(file.toPath(), response.getOutputStream());
   }
}

Both users are having the same pdf displayed.

I think this is due to the fact that the variable for the session attribute is the same, but if i create a separate variable for each table line, how can I distinguish them in the webservlet code?

问题已解决。

如果有人感兴趣,这里是需要做的事情:

JSP:

<object data="${pageContext.request.contextPath}/cv/<%= user.getCV()%>" type="application/pdf"/>

Webservlet:

@WebServlet(urlPatterns={"/cv/*"})
public class CV extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException {
String url = request.getRequestURL().toString(); //gets full url address

if(url.split("/cv/").length == 2) {
    String cp = url.split("/cv/")[1] + ".pdf";

    //white spaces become %20, replace them
    File file = new File(cp.replace("%20", " ")); 
    response.setHeader("Content-Type", 
 getServletContext().getMimeType(file.getName()));
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "inline; filename=\"*.pdf\"");
    try {
        Files.copy(file.toPath(), response.getOutputStream());
    } catch (IOException ex) {
    }
  }
 }
}