servlets - 如何在 GlassFish 中为自动传送的文件设置 Content-Type?

标签 servlets glassfish mime-types

将 .war 文件部署到 GlassFish Server(当前为 4.1)时,GF 服务器会自动从 WEB-INF/ 传送文件。文件夹。 (除非我通过指定一个 Servlet 来覆盖它们的地址。)

实际上,在部署.war 文件到GF 服务器时,它会提取WEB-INF/ 下的那些文件。至 {gf-home}/glassfish/domains/domain1/applications/{app-name} .
然后它在访问 http://{hostname}:8080/{app-name}/{path} 时传递它们.

现在访问 .json 文件时,服务器不会发送 HTTP Content-Type: application/json标题。
这导致页面无法正确加载,FireFox 控制台向我显示 XML Parsing Error: not well-formed异常(exception),即使文件内容完全相同。
所以我的猜测是缺少 Content-Type 标签。

如何为应用程序/项目本身更改此 MIME 映射?

从我目前看到的页面来看,可以在 {gf-home}/glassfish/domains/domain1/default-web.xml 中重新定义这种行为。文件,定义 mime-mapping .但假设我无法访问该文件,只能上传 .war 文件。有什么解决办法吗?是否可以打包 default-web.xml .war 文件的某处?

我目前能想到的另一个解决方案是用 servlet 覆盖特定的 .json 文件的地址并添加 Content-Type Java 中的头文件。但我不确定在运行时访问和读取 .json 文件是否有一种万无一失的方法,但无需将它们移动到 Java 源代码中的任何位置,而是将它们留在 WEB-INF/文件夹中?有什么建议?

最佳答案

How can I change this mime-mapping for the app/project itself?



通过声明 <mime-mapping> webapp 自己的条目 /WEB-INF/web.xml .

从 Servlet 3.0 版开始,web.xml文件成为可选的。这或许可以解释为什么你找不到人。你可以在 webapp 中提供你自己的。 GlassFish 4.1 是一个支持 Servlet 3.1 的容器,所以下面的 Servlet 3.1 兼容 web.xml应该让你开始:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!-- Config here. -->
</web-app>

在您的特定情况下,您将需要以下 MIME 映射:

    <mime-mapping>
        <extension>json</extension>
        <mime-type>application/json</mime-type>
    </mime-mapping>

也可以看看:
  • What is conf/web.xml used for in Tomcat as oppsed to the one in WEB-INF?
  • How to set the content type on the servlet
  • How to find servlet API version for glassfish server?
  • Servlet 3.1 specification (PDF) chapter 10.13
  • 关于servlets - 如何在 GlassFish 中为自动传送的文件设置 Content-Type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577467/

    相关文章:

    php - 为什么 PHP 不为 json 文件返回正确的 mime?

    python - 在Python中检测文件是否是视频?

    当 content-type 为 application/x-www-form-urlencoded 时,Java 读取 POST 数据

    java - 无法在 eclipse 中将数据从 servlet 发送到 jsp 页面。怎么解决这个问题?

    java - 如何部署 webapp 并创建其资源

    java - 帮助 Web 服务 vector Java Glassfish

    java - GlassFish 上的 ical4j 订阅服务

    java - php 和 jsp 中的 session ID

    android - 如何在本地机器上为 Android 手机设置服务器?

    java - 如何将未经授权的用户重定向到某个JSP页面? (使用基于声明性角色的授权)