2015-10-30 21 views
0

我在spring mvc项目中创建了一个简单的jsp页面。但我无法从图像文件夹加载图像。我尝试过使用实际路径和上下文路径,但仍无法将图像加载到jsp文件中。无法加载jsp页面中的图像

真实路径:

<% 
String realPath = application.getRealPath("/"); 
%> 

<img src="<%=realPath%>images\logo.png" alt="student" title="student"> 

上下文路径:

<% 
String contextPath = request.getContextPath(); 
%> 
<img src="<%=realPath%>images\logo.png" alt="student" title="student"> 

我的项目文件夹struture看起来像

enter image description here

我错过了什么吗?我需要在web.xml中进行任何配置吗?

有什么建议吗?

回答

1

您必须配置静态资源,如图片,像js和css文件:

<mvc:resources mapping="/images/**" location="/images/"/> 

在上面的例子,从这个URL模式的任何请求/图片/ **,Spring就会查找的资源从/ images文件夹。

+0

。 – Andreas

+0

谢谢。这个对我有用。但我有小问题。假设我有10个静态资源文件夹(css,js,images .....),那么我需要映射所有10个文件夹吗?或者,如果我复制资源文件夹中的所有文件夹并仅配置资源文件夹(如)。这会让人感觉如何?任何建议请 – Vinod

+0

您可以为每个文件类型添加许多配置,例如: tcharaf

1
  1. 您不能使用真实路径,因为浏览器不会与webapp在同一台机器上!
  2. 您不能使用\,因为URL必须使用/
  3. 不要在JSP中使用Java代码,尤其是当要使用EL变量时。
  4. 您错过了/。引用javadoc的getContextPath()

    路径以“/”字符开头,但不以“/”字符结尾。

这是如何做到这一点:只有当`/ *`被映射到Spring需要

<img src="${pageContext.request.contextPath}/images/logo.png" alt="student" title="student">