Spring MVC: CSS return

My goal is to combine / minimize all css files and return the result as String.

Here is my Spring testing method:

@RequestMapping(value = "/stylesheet.css", method = RequestMethod.GET, produces = "text/css")
@ResponseBody
public void css(HttpServletResponse response) {
    File path = new File(servletContext.getRealPath("/WEB-INF/includes/css/"));

    File[] files = path.listFiles(...);

    for (File file : files) {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();

        is.close();
    }
}

This works with Chrome, Firefox, and Safari, but not with IE and Opera.

After some checks in inspectors, the URL is https://host/project/stylesheet.cssloaded in each browser. I see the content, but it does not seem to be recognized as text/css.

Also, even with produces = "text/css"I do not see the content-typehttp header in all browsers.

Error log in IE:

CSS ignored because of mime type incompatibility

Does anyone know how to do this correctly?

Work code:

@RequestMapping(value = "/stylesheet.css", method = RequestMethod.GET)
public ResponseEntity<Void> css(HttpServletResponse response) {
    response.setContentType("text/css");

    File path = new File(servletContext.getRealPath("/WEB-INF/includes/css/"));

    File[] files = path.listFiles(...);

    for (File file : files) {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        IOUtils.closeQuietly(is);
    }

    response.flushBuffer();

    return new ResponseEntity<Void>(HttpStatus.OK);
}
+3
source share
2 answers

I suspect the issue is usage related HttpServletResponse.flushBuffer().

As the API shows HttpServletRequest:

. , .

, Spring Content-Type HttpServletResponse . , HttpServletResponse.flushBuffer(), .

:

  • HttpServletResponse HttpServletResponse.flushBuffer()
  • HttpServletRequest.flushBuffer()
+5

, @ResponseBody. , Content-Type. , ResponseEntity ( void), Spring, .

@RequestMapping(value = "/stylesheet.css", method = RequestMethod.GET)
public ResponseEntity css(HttpServletResponse response) {

    // Set the content-type
    response.setHeader("Content-Type", "text/css");

    File path = new File(servletContext.getRealPath("/WEB-INF/includes/css/"));

    File[] files = path.listFiles(...);

    for (File file : files) {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        IOUtils.closeQuietly(is);
    }

    response.flushBuffer();

    return new ResponseEntity(HttpStatus.OK)
}
+4

All Articles