0

This sounds like an obvious question but it's not. I've been through a bunch of answers and none ask or say what the URL is to the file.

I want to be able to host a .dtd file so my xml can reference it like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE Somexml SYSTEM "http//:example.com/my.dtd">
<Somexml>
</Somexml>

I've tried putting my file in /static/ but there's no evidence that Tomcat is hosting this file.

These are some of the questions I've already looked at. None of them ask or state the URL of the file, so this question is not a duplicate: How to serve static content from tomcat https://serverfault.com/questions/143667/how-to-access-a-simple-file-or-folder-from-tomcat-webapps-folder How to serve static files in my web application on Tomcat Simplest way to serve static data from outside the application server in a Java web application https://www.moreofless.co.uk/static-content-web-pages-images-tomcat-outside-war/

Philip Rego
  • 552
  • 4
  • 20
  • 35

1 Answers1

1

You can create servlet:

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getPathInfo().substring(1);
        File file = new File(PATH_TO_LIBRARY_WHERE_FILES_ARE_STORED, filename);
        response.setHeader("Content-Type", getServletContext().getMimeType(filename));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }    
}

Then url to the file in this case will be: http://www.yourdomain.com/images/name_of_file.xxx

Milkmaid
  • 1,659
  • 4
  • 26
  • 39
  • Can PATH_TO_LIBRARY_WHERE_FILES_ARE_STORED be a folder I deploy in a WAR? So I can have all my files in a single bundle. Or do I have upload my files to the servers on each environment, and use an absolute path for PATH_TO_LIBRARY_WHERE_FILES_ARE_STORED? – Philip Rego Oct 12 '17 at 05:42
  • You don't need to create a Servlet. The default Servlet will do it all perfectly well. All you have to do is get the paths and URLs correct. – user207421 Oct 12 '17 at 05:48
  • @PhilipRego yes you can. But make sure your path is correct. – Milkmaid Oct 12 '17 at 05:51
  • This worked for me. Thank you. I don't know who downvoted it. The default path for me was '/' so I had to specify the absolute path. I used "/app/apache-tomcat-7.0.75/webapps/api/WEB-INF/classes/my.dtd" this file was kept in my project as /static/my.dtd. Not sure where the static folder went but it's working fine. – Philip Rego Oct 12 '17 at 23:17