Issue
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:\\1234.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.
Solution
You have done two things wrong
Your servlets neet to be inside the source directory, not in the web root.
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")
.
Answered By - dan1st
Answer Checked By - Willingham (JavaFixing Volunteer)