gpt4 book ai didi

java - HttpServlet 请求 : How to determine Content-Type of requested asset

转载 作者:行者123 更新时间:2023-11-30 11:57:58 24 4
gpt4 key购买 nike

我正在使用 Jetty 编写一个快速而简单的静态文件服务器。我需要为每个响应设置 Content-Type:

HttpServletResponse.setContentType("content/type");

对于给定的文件请求,我如何可靠地确定要设置的内容类型?是检查文件扩展名的问题,还是有更复杂的方法? (例如,如果没有文件扩展名,或者扩展名不反射(reflect)内容类型怎么办?)

谢谢理查德

最佳答案

由于您在问题中使用了 HttpServletResponse 对象,我假设您的 Controller 中有可用的 ServletContext。我只是使用 servletContext 提供的方法解决了同样的问题。

因为你正在编写一个文件服务器,你可以在 ServletContext 的 getMimeType 方法中传入文件的路径,它应该返回 mimeType,如果它可以确定的话。

String path = "/js/example.js";
String mimeType = getServletContext().getMimeType(path);
resp.setContentType(mimeType); // HttpServletResponse object

NOTE: Sets the content type to "application-x/javascript" in this particular example.

附加信息:我相信此解决方案还假定您的文件存储在 ServletContext 可访问的位置。如果没有,那么其他解决方案之一可能是最好的。

关于java - HttpServlet 请求 : How to determine Content-Type of requested asset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3433844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com