我知道,已经有几个类似的问题,但是没有一个能解决我的问题。 我有一个简单的JSP
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Home Page</h3>
<table>
<tr>
<td>aha</td>
</tr>
</table>
${data.image}
<img src="images/wappen.jpg"/>
<img src="/images/wappen.jpg"/>
<img src="../images/wappen.jpg" alt=""/>
</body>
</html>
没有图像显示。 JSP位于WEB-INF / views中的战争中 jpg位于战争中的文件夹图像中。
目录结构:
-WebContent
- images (here are my jpgs)
- META-INF
- WEB-INF
- lib
- views (here are my jsps located)
通过WebServlet调用jsp:
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/homeView.jsp");
dispatcher.forward(request, response);
答案 0 :(得分:0)
我不知道这是否正确,但至少我找到了解决方法:
创建一个Webservlet来处理上下文图像:
返回为响应
import java.io.BufferedInputStream; 导入java.io.BufferedOutputStream; 导入java.io.FileInputStream; 导入java.io.IOException; 导入java.lang.invoke.MethodHandles;
import javax.servlet.ServletException; 导入javax.servlet.ServletOutputStream; 导入javax.servlet.annotation.WebServlet; 导入javax.servlet.http.HttpServlet; 导入javax.servlet.http.HttpServletRequest; 导入javax.servlet.http.HttpServletResponse;
导入org.slf4j.ext.XLogger; 导入org.slf4j.ext.XLoggerFactory;
@WebServlet(urlPatterns = {“ / Images / *”}) 公共类DisplayImageServlet扩展了HttpServlet { / **保持记录器* / 最终的XLogger logger = XLoggerFactory.getXLogger(MethodHandles.lookup()。lookupClass());
private static final long serialVersionUID = 1L;
public DisplayImageServlet(){ 超(); }
@Override 受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应) 引发ServletException,IOException { HttpServletRequest req =(HttpServletRequest)请求;
String realRootPath = request.getServletContext().getRealPath("");
String servletPath = req.getServletPath();
String image = req.getRequestURI();
String pathInfo = request.getPathInfo();
logger.debug("realRootPath = " + realRootPath);
logger.debug("servletPath = " + servletPath);
logger.debug("image = " + image);
logger.debug("pathInfo = " + pathInfo);
String imageRealPath = realRootPath +servletPath+pathInfo;
logger.debug("imageRealPath = " + imageRealPath);
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream(imageRealPath);
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
@Override 受保护的void doPost(HttpServletRequest请求,HttpServletResponse响应) 引发ServletException,IOException { logger.debug(“ doPost”); doGet(请求,响应); }
}