Issue
I'm downloading a file without an extension when I go to a servlet
This is code of doGet method (these are just test lines, don't take them seriously):
try {
PrintWriter pw = response.getWriter();
pw.write("test");
pw.println(request.getParameter("a"));
DAOFactory m = DAOFactory.getDAOFactory(1);
Connection conForTests = MySQLDAOFactory.getConnection();
UserDao s = m.getUserDao();
boolean check = s.validateUser("test1","test1",conForTests);
pw.write(String.valueOf(check));
User user = s.findUser("test1",conForTests);
int id = user.getUserId();
pw.write(11);
} catch (SQLException|IOException sqlException) {
System.out.println("asdsad");
sqlException.printStackTrace();
}
System.out.println("asdsad");
}
And I checked all the lines removing them line by line and I have found out that at this line:
pw.write(11);
And that's 11 was a user id so to not retrieve that id each time, I have just written 11. The servlet starts not showing a page, but downloading a file without an extension.
I checked that 11 number is staying for a Vertical Tab in ASCII table. Why is 11 code in ASCII table makes browser to not displaying but downloading file?
And that is content of this file:
Solution
Why am I downloading a file with no extension using servlet?
Because you just opened a response stream and started writing into it. In lay terms, you are just sending some bytes back to the browser, but the browser doesn't know what does bytes are. Is it html? Is it plain text? Is it an image? Some other thing?
So before starting to write the response, you need to say what that response is by setting a content type. Replace this code of yours:
try {
PrintWriter pw = response.getWriter();
....
with:
try {
response.setContentType("text/html")
PrintWriter pw = response.getWriter();
....
or whatever content type you prefer (a text/plain
can also work for what you are doing).
See also:
- what is the use of "response.setContentType("text/html")" in servlet
- Java - Default contentType for Servlet
Answered By - Bogdan
Answer Checked By - Mary Flores (JavaFixing Volunteer)