Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Content-Type for auto-delivered file in GlassFish?

When deploying a .war file to a GlassFish Server (4.1 currently), the GF server automatically delivers files from the WEB-INF/ folder. (Unless I override their addresses by specifying a Servlet, that is.)

Actually when deploying the .war file to the GF server, it extracts those files under WEB-INF/ to {gf-home}/glassfish/domains/domain1/applications/{app-name}. Then it delivers them when accessing http://{hostname}:8080/{app-name}/{path}.

Now when accessing .json files, the server does NOT send the HTTP Content-Type: application/json header. This results in the page not loading properly, FireFox console showing me a XML Parsing Error: not well-formed exception, even though the file contents are exactly the same. So my guess is that it's the missing Content-Type tag.

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

From the pages I have seen so far, it is possible to redefine this behaviour in the {gf-home}/glassfish/domains/domain1/default-web.xml file, defining the mime-mapping. But presuming I cannot access that file, only upload .war files. Is there any solution? Is it possible to pack a default-web.xml somewhere into the .war file?

The other solution I can think of at the moment is to override the specific .json files' addresses with a servlet and adding the Content-Type header in Java. But I'm not sure if there is a foolproof way of accessing and reading the .json files at runtime, but without moving them anywhere in the Java source code, but leaving them in the WEB-INF/ folder? Any suggestions?

like image 413
JayC667 Avatar asked Nov 30 '17 15:11

JayC667


1 Answers

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

By declaring the <mime-mapping> entries in webapp's own /WEB-INF/web.xml.

Since Servlet version 3.0, the web.xml file became optional. That'll perhaps explain why you could find no one. You can just supply your own in the webapp. GlassFish 4.1 is a Servlet 3.1 capable container, so the below Servlet 3.1 compatible web.xml should get you started:

<?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>

In your specific case, you'll need the below mime mapping in there:

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

See also:

  • 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
like image 175
BalusC Avatar answered Nov 15 '22 04:11

BalusC