javaEE 静态文件处理问题
我在
web.xml
里添加如下的配置,来过滤图片静态文件,如果出现404我怎么交给 Spring 来处理,也就是图片文件如果不存在,我就交给 Spring 来处理生成一个缩略图
xml
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/file/*</url-pattern> </servlet-mapping>
Answers
这种方式行不通,首先不能先通过
Servlet
处理,失败后再转交给
Spring
如果你把全部的
/file/*
都交给
Servlet
处理,那样即使404也无法通知到
Spring
如果通过
mvc:resources
这种方式其实也无法处理404,静态资源404后同样没有通过
Spring
进行错误处理
<mvc:resources mapping="/file/**" location="/file/"/>
不建议这样搞,如果真的是核心非常影响体验的业务,到一种可行但是比较挫的方法
这部分文件路径直接通过
Spring
或者
Servlet
处理,接收到文件名后如果找不到该文件,返回默认文件。
Spring
实现
@ResponseBody
@RequestMapping(value = "/file/{filename:.+}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testPhoto(@PathVariable("filename") String filename) throws IOException {
File file = new File("/uploads/" + filename);
if(!file.exists()) { // 不存在就走默认
file = new File("/uploads/default.jpg");
}
// 下面的部分按自己想法实现
byte[] bytes = new byte[(int)file.length()];
FileUtils.writeByteArrayToFile(file, bytes);
return bytes;
}
我已经尽力了,看有人有更好的办法没有