加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring MVC:返回CSS

发布时间:2020-12-15 04:42:12 所属栏目:Java 来源:网络整理
导读:我的目标是合并/缩小所有css文件并将结果作为String返回. 这是我的Spring测试方法: @RequestMapping(value = "/stylesheet.css",method = RequestMethod.GET,produces = "text/css")@ResponseBodypublic void css(HttpServletResponse response) { File pat
我的目标是合并/缩小所有css文件并将结果作为String返回.

这是我的Spring测试方法:

@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();
    }
}

这适用于Chrome,Firefox和Safari,但不适用于IE和Opera.

在检查员中进行一些检查后,每个浏览器都会加载URL https://host/project/stylesheet.css.我可以看到内容但它似乎没有被识别为text / css.

此外,即使使用produce =“text / css”,我也无法在所有浏览器中看到内容类型的http标头.

IE中的错误日志:

CSS ignored because of mime type incompatibility

有谁知道如何正确地做到这一点?

工作代码:

@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);
}

解决方法

我怀疑问题是由于您使用了HttpServletResponse.flushBuffer().

正如HttpServletRequest的API所述:

Forces any content in the buffer to be written to the client. A call
to this method automatically commits the response,meaning the status
code and headers will be written.

我的假设是Spring会在控制器上的方法返回后尝试在HttpServletResponse上设置Content-Type标头.但是,因为您已经通过调用HttpServletResponse.flushBuffer()提交了响应,所以它无法执行此操作.

我会尝试:

>在调用HttpServletResponse.flushBuffer()之前,将HttpServletResponse注入控制器并在代码中自己设置标题>删除你对HttpServletRequest.flushBuffer()的使用

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读