如何将缓存控制头添加到存储在spring mvc服务的数据库中的图像

时间:2016-02-29 05:24:21

标签: spring spring-mvc caching spring-security

我正在尝试使用Spring MVC控制器提供一些图像,图像存储在数据库中 这是我的控制器的样子。

@RequestMapping("/getEmployeeImage/{id}")
public String getEmployeeImage(@PathVariable("id") Integer id, HttpServletResponse response, HttpServletRequest request) throws IOException {
    Employee employee = employeeSercice.getEmployee=(id);

    if (employee.getPhoto() != null) {
        response.setContentType("image/jpg");
        byte buf[] = employee.getPhoto();
        try {
            response.getOutputStream().write(buf);
            BufferedOutputStream output = null;
            output = new BufferedOutputStream(response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

    }
    return null;
}

我如何启用浏览器端缓存?我已经尝试过response.setHeader(" Cache-Control"," max-age = 361440");但没有工作

1 个答案:

答案 0 :(得分:0)

对于缓存控制,您可以使用注释

@CacheControl(isPublic = true, maxAge = 100, sMaxAge = 100), 

之后使用Spring MVC拦截器将注释呈现给HTTP Header。

另一种方式:

int ageValue=100;
String cacheControl = CacheControlHeader.newBuilder()
      .setCacheType(CacheType.PUBLIC)
      .setMaxAge(ageValue)
      .setsMaxAge(ageValue).build().stringValue();

    response.addHeader("Cache-Control", cacheControl);
}
相关问题