英文:
Servlet page display source code instead of image
问题
这是我的index.jsp:
<%@page contentType="text/html; ISO-8859-1" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="Servlet.java">获取图片</a>
</body>
</html>
链接到Servlet.java:
@WebServlet(name = "Servlet")
public class Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
FileInputStream fin = new FileInputStream("D:\34.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
我的结果:https://i.stack.imgur.com/Lkuo8.png
我尝试设置不同的响应内容类型,但似乎没有生效。
英文:
This is my index.jsp
<%@page contentType="text/html; ISO-8859-1" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="Servlet.java">Get IMG</a>
</body>
</html>
which link to Servlet.java
@WebServlet(name = "Servlet")
public class Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
FileInputStream fin = new FileInputStream("D:\34.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
My result : https://i.stack.imgur.com/Lkuo8.png
I did try to set different response contentType but nothing seems to work.
答案1
得分: 0
你做了两件错误的事情:
-
你的Servlet应该放在源代码目录中,而不是Web根目录中。 <br/>
如果文件在Web根目录中,它们将原样发送,除非服务器知道如何解析它们(例如jsp文件)。 -
不要链接到
Servlet.java
,而应该链接到Servlet
,如果你想要通过@WebServlet(name = "Servlet")
来指定它的位置。
英文:
You have done two things wrong
-
Your servlets neet to be inside the source directory, not in the web root. <br/>
If the files are inside the web root, they will be sent as is except the server knows how to parse them(like jsp files). -
Do not link to
Servlet.java
but toServlet
if you want to have specified it to be located there using@WebServlet(name = "Servlet")
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论