返回介绍

12.2 范例 1:隐藏资源

发布于 2025-04-22 20:10:04 字数 4512 浏览 0 评论 0 收藏

download 应用程序展示了如何向浏览器发送文件。在这个应用程序中,由 ResourceController 类处理用户登录,并将一个 secret.pdf 文件发送给浏览器。secret.pdf 文件放在 WEB-INF/data 目录下,因此不可能直接访问。只有得到授权的用户,才能看到它。如果用户没有登录,应用程序就会跳转到登录页面。

清单 12.1 中的 ResourceController 类提供了一个控制器,负责发送 secret.pdf 文件。只有当用户的 HttpSession 中包含一个 loggedIn 属性时,表示该用户已经成功登录,才允许该用户访问。

清单 12.1 ResourceController 类

package controller;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import domain.Login;

@Controller
public class ResourceController {

  private static final Log logger =
    LogFactory.getLog(ResourceController.class);

  @RequestMapping(value="/login")
  public String login(@ModelAttribute Login login, HttpSession
      session, Model model) {
    model.addAttribute("login", new Login());
    if ("paul".equals(login.getUserName()) &&
         "secret".equals(login.getPassword())) {
      session.setAttribute("loggedIn", Boolean.TRUE);
      return "Main";
    } else {
      return "LoginForm";
    }
  }

  @RequestMapping(value="/download-resource")
  public String downloadResource(HttpSession session,
      HttpServletRequest request, HttpServletResponse response,
      Model model) {
    if (session == null ||
        session.getAttribute("loggedIn") == null) {
      model.addAttribute("login", new Login());
      return "LoginForm";
    }
    String dataDirectory = request.
        getServletContext().getRealPath("/WEB-INF/data");
    Path file = Paths.get(dataDirectory, "secret.pdf");
    if (Files.exists(file)) {
      response.setContentType("application/pdf");
      response.addHeader("Content-Disposition",
          "attachment; filename=secret.pdf");

      try {
        Files.copy(file, response.getOutputStream());
      } catch (IOException ex) {
      }
    }
    return null;
  }
}

控制器中的第一个方法 login,将用户带到登录表单。

LoginForm.jsp 页面如清单 12.2 所示。

清单 12.2 LoginForm.jsp 页面

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
<style type="text/css">@import url("<c:url
    value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
<form:form commandName="login" action="login" method="post">
  <fieldset>
    <legend>Login</legend>
    <p>
      <label for="userName">User Name: </label>
      <form:input id="userName" path="userName"
           cssErrorClass="error"/>
    </p>
    <p>
      <label for="password">Password: </label>
      <form:password id="password" path="password"
        cssErrorClass="error"/>
    </p>
    <p id="buttons">
      <input id="reset" type="reset">
      <input id="submit" type="submit"
        value="Login">
    </p>
  </fieldset>
</form:form>
</div>
</body>
</html>

成功登录所用的用户名和密码必须在 login 方法中进行硬编码。例如,用户名必须为 paul,密码必须为 secret。如果用户成功登录,他就会被转到 Main.jsp 页面(清单 12.3)。Main.jsp 页面中包含了一个链接,用户可以单击它来下载文件。

清单 12.3 Main.jsp 页面

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Download Page</title>
<style type="text/css">@import url("<c:url
    value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
  <h4>Please click the link below.</h4>
  <p>
    <a href="resource_download">Download</a>
  </p>
</div>
</body>
</html>

ResourceController 类中的第二个方法 downloadResource,它通过验证 session 属性 loggedIn 是否存在,来核实用户是否已经成功登录。如果找到该属性,就会将文件发送给浏览器。如果没有找到,用户就会转到登录页面。注意,如果使用 Java 7 或其更高版本,则可以使用其新的 try-with-resources 特性,从而更加安全地处理资源。

通过调用以下 URL 中的 FileDownloadServlet,可以测试 download 应用程序。

http://localhost:8080/download/login

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。