在JSP中显示图像(html)

时间:2014-04-07 20:21:15

标签: java html image jsp

我在JSP类中显示图像非常意外。我已将我的图片放在此文件夹中:C:\Users\jacob\workspace2\BuildRoomClientProject\WebContent\img。当我使用<img src="img/lund.png" height="50" width="50">时,图像将无法显示,就像eclipse找不到任何名为lund.png的图片一样。我做错了什么?

这是我的 JSP-code

<%@ page contentType="text/html;charset=windows-1252"%> 

<%@ page import = "org.ics.ejb.Building" %> 
<%@ page import = "org.ics.ejb.Room" %> 
<%@ page import = "org.ics.ejb.RoomId" %> 
<%@ page import = "java.util.List" %> 
<%@ page import = "java.util.Iterator" %>
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title> 
Show Rooms 
</title> 
</head> 
<body bgcolor="Pink"> 
<h2> 
Rooms: 
</h2> 

<%List<Room> r = (List<Room>)request.getAttribute("rooms"); %>
<% for (Room r1 : r){
out.println(r1.getBname() + "  " + r1.getId().getrcode());
}%>

<p> 
</p> 

<form action="/BuildRoomClientProject/TestClientServlet" method="post"> 
<input type="submit" name="submit" value="Tillbaka"> 
<input name="operation" value="searchbuilding" type="hidden"> 
</form> 
<img src="img/lund.png" height="50" width="50">
</body> 
</html>

2 个答案:

答案 0 :(得分:1)

img文件夹并行的webapp文件夹下创建一个文件夹WEB-INF,然后将图片lund.png放在那里。

WebContent
|
|__abc.jsp
|__WEB-INF
|__img
   |
   |__lund.png

尝试使用简单的jsp文件,如下所示:

<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show Rooms</title>
</head>
<body bgcolor="Pink">
    <img src="img/lund.png" height="50" width="50">
</body>
</html>

答案 1 :(得分:0)

原因:

我认为问题在于,当您在jsp文件中指定路径(例如img/lund.png)时,它将向您的服务器发送请求以获取此图像。您可能使用urlPattern = /定义了servlet,并且图像路径(img/lound.png)与此模式匹配(/包含/ing/lund.png),因此您的自定义servlet正在执行图像请求,但是它不包含任何返回图像的逻辑。

解决方案:

  • 您可以按照本文中的描述为文件创建servlet:FileServlet

  • 或者您可以更改自定义servlet urlPattern,以使其与文件夹不相交。例如:servlet_url_pattern = "servlets/myServlet"images_folder = "img/myImages"

P.S。我是servlet的新手,因此在某些情况下我可能会错了,但是它适用于我的项目。

相关问题