Java 正在从src/main/resources/读取资源。。春季MVC
我有个问题让我头疼。 首先,我的项目结构如下所示。 我制作了一个控制器,它将图像(*.png)文件返回到相应的请求 控制器的代码写在下面Java 正在从src/main/resources/读取资源。。春季MVC,java,spring,spring-mvc,model-view-controller,Java,Spring,Spring Mvc,Model View Controller,我有个问题让我头疼。 首先,我的项目结构如下所示。 我制作了一个控制器,它将图像(*.png)文件返回到相应的请求 控制器的代码写在下面 @控制器 公共类图像控制器{ @GetMapping(value=“/ImageStore.do”,products=MediaType.IMAGE\u PNG\u value) public@ResponseBody字节[]getStoreImage(HttpServletRequest请求)引发IOException{ 字符串image\u name=r
@控制器
公共类图像控制器{
@GetMapping(value=“/ImageStore.do”,products=MediaType.IMAGE\u PNG\u value)
public@ResponseBody字节[]getStoreImage(HttpServletRequest请求)引发IOException{
字符串image\u name=request.getParameter(“image\u name”);
Resource=null;
试一试{
resource=新类路径资源(“/images/stores/”+图像名称);
if(资源==null){
抛出新的NullPointerException();
}
}捕获(NullPointerException e){
resource=newclasspathresource(“/images/stores/noimage.png”);
}
InputStream InputStream=resource.getInputStream();
返回IOUtils.toByteArray(inputStream);
}
}
问题1。我添加了try catch
短语来发送noimage.png
,如果请求参数错误,或者请求参数image\u name
的文件名不存在。但它似乎不起作用,它让我觉得
无法打开类路径资源[images/stores/noima.png],因为它不存在
(如果您需要了解完整的堆栈跟踪,我将在下面进行评论。)
问题2。我在文件夹
/resources/images/stores/
中有两个图像文件,hello.png
和noimage.png
。我可以正确地读取noimage.png
,但是如果我发出请求localhost:8080/ImageStore.do?image\u name=hello.png
,那么它就会出错,在Q1中创建相同的日志。没有理由认为构造函数会导致空值
您得到的异常可能来自getInputStream
方法,该方法将抛出
FileNotFoundException-如果基础资源不存在
IOException-如果无法打开内容流
稍微调整一下可能会有所帮助
@Controller
public class ImageController {
@GetMapping(value = "/ImageStore.do", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getStoreImage(HttpServletRequest request) throws IOException {
InputStream is = null;
try {
String image_name = request.getParameter("image_name");
is = new ClassPathResource("/images/stores/" + image_name).getInputStream();
} catch(FileNotFoundException e) {
is = new ClassPathResource("/images/stores/noimage.png").getInputStream();
}
return IOUtils.toByteArray(is);
}
}
您应该包括堆栈跟踪和异常消息,这可能有助于理解您的第二个查询,但我会检查文件是否确实存在,以及您使用的确切名称。首先,感谢@ptomli的回复。我试过了,但似乎没有解决我的问题。如果您看到上面的图片“我的项目结构”,您可以看到在/resources/images/stores/
下有hello.png
和noimage.png
。如果我请求localhost:8080/ImageStore.do?image\u name=hello.png
,它会显示正确的图像,但是如果我请求localhost:8080/ImageStore.do?image\u name=noimage.png,它会显示FileNotFoundException页面。spring是否可能无法从resources文件夹中读取超过1个文件?java.io.FileNotFoundException:无法打开类路径资源[images/events/noimage.png],因为它不存在
。您最后的评论显示在事件
子目录中查找文件时出错,这表明生成错误的代码与我们上面看到的代码不同。是的,但是如果事件
子目录出错,它也应该无法读取hello.png
文件,我通过将noimage.png
的名称重构为default.png
解决了这个问题。似乎名称noimage
是某种保留字或什么:)谢谢你的帮助!