【问题标题】:How to redirect page to static file in Spring Boot?如何在 Spring Boot 中将页面重定向到静态文件?
【发布时间】:2016-03-14 04:10:51
【问题描述】:

如何在 Spring Boot (MVC) 中重定向页面 Web 请求/请求映射以指向静态文件(例如:.txt、.json、.jpg、.mp4 等)。我的 Spring Boot 项目中只有一个 application.properties 文件和 @Controllers。

我希望用户在向浏览器中的 url 发出 Web 请求时被要求下载文件(而不是使用它来尝试呈现页面,就像使用 .html、.jsp 一样)

【问题讨论】:

  • 当用户点击链接时下载文件?你的意思是redirecting to static file 吗?

标签: java spring-mvc spring-boot


【解决方案1】:

您可以在 Spring 中使用“redirect:”前缀进行重定向。来自Spring documentation

诸如redirect:/myapp/some/resource 之类的逻辑视图名称将相对于当前Servlet 上下文进行重定向,而诸如redirect:http://myhost.com/some/arbitrary/path 之类的名称将重定向到绝对URL。

一个例子是:

@RequestMapping("/redirectToResource")
protected String redirect(@RequestParameter("resource") String resource) {
    return "redirect:/myapp/some/" + resource;
}

您可以将要提供的静态资源直接放在类路径中的以下任何位置(请参阅Serving static resources):

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    "classpath:/META-INF/resources/", "classpath:/resources/",
    "classpath:/static/", "classpath:/public/" };

【讨论】:

  • 如果我错了,请纠正我,但使用“重定向:”会导致最终用户到达的 url 被重写。我不确定是否需要这种行为。它还仅限于提供已经作为静态资源可用的资源。
  • 是的,它会导致浏览器重定向。要动态加载文件,您始终可以将 @RequestParameter 作为方法参数。是的,该文件由 Spring Boot 作为静态资源提供。
【解决方案2】:

您可以通过告诉响应您希望附加可下载文件来实现此目的。然后您可以简单地编写您想要下载的内容。

这是一个例子:

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/myredirect", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadFile(HttpServletResponse response) {
    // Remove this instruction if you wish to disable the download dialog.
    response.setHeader("Content-Disposition", "attachment; filename=filename.ext");

    // Load your file content as byte.
    byte[] fileContent = IOUtils.toByteArray(new ClasspathResource("myfile").getIntputStream());

    response.getOutputStream().write(fileContent);
}

另一方面,如果您只是想直接映射到静态文件。您可以使用 Spring Boot Starter Web 的默认 public 文件夹。

默认情况下,在classpath:/public 中找到的任何文件都将映射到/*

【讨论】:

  • 谢谢丹尼尔。我有一个问题。现在,我可以通过转到根路径(例如:www.mysite.com/myfile.txt)来访问我的静态文件,但我希望能够在类似(www.mysite.com /myredirect) .... 我如何配置项目以映射请求以重定向到静态文件?
  • 您好,我已经更新了我的 sn-p 来回答您的问题。您需要从 RequestMapping 值定义您的重定向 url。然后从类路径或绝对路径将文件加载为字节数组。如你所愿。祝你好运。如果您想删除下载行为,只需删除 setHeader sniper。
  • 谢谢!我会试试这个!
  • 我一直在再次阅读您的评论,我认为您不明白您的类路径的公共文件夹中可用的任何资源都可以从根路径获得。例如:public/img/logo.png 中的文件可从 URL www.mysite.com/img/logo.png 获得。如果您更喜欢使用自定义 URL,那么请求映射就是您的最佳选择。
猜你喜欢
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多