简体   繁体   中英

Display image in JSP (html)

I have a very unexpected hard time to display an image in my JSP-class. I have put my Image in this folder: C:\\Users\\jacob\\workspace2\\BuildRoomClientProject\\WebContent\\img . When I use <img src="img/lund.png" height="50" width="50"> the image won't show, it's like eclipse cannot find any picture named lund.png . What am I doing wrong?

And this is my 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>

Create a folder img under your webapp folder in the parallel of WEB-INF folder and put the image lund.png there.

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

Try with simple jsp file as shown below:

<%@ 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>

Cause:

I think that problem is that when you specify path in your jsp file (like img/lund.png ), it sends request to your server to get this image. You probably defined servlet with urlPattern = / and your image path ( img/lound.png ) matches this pattern ( / contains /ing/lund.png ), so your custom servlet is executing for image request, but it doesn't contain any logic to return image.

Solutions:

  • You can create servlet for files as described in this post: FileServlet

  • Or you can change your custom servlet urlPattern so it would not intersect with you files folder. For example: servlet_url_pattern = "servlets/myServlet" and images_folder = "img/myImages"

PS I am new to servlets, so I may be wrong in some cases, but it works with my project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM