Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to set content-type to html in this Java Servlet?

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.Date;

public class HelloServlet extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
    {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>only for test</title></head><body>Hello, world!html version</body></html>");
        out.flush();
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
    {
        doGet(request, response);
    }
}

If I set the content-type to xhtml, then the web-browser would automatically open the save-file dialog. Why would this happen?

like image 263
Jichao Avatar asked Jan 30 '26 10:01

Jichao


1 Answers

First of all, note that the right content-type for xhtml is not xhtml or text/xhtml, but application/xhtml+xml.

Anyway, you'll need to check whether the user agent can actually accept this content-type by examining the Accept HTTP request header. According to the W3C recommendation:

  1. If the Accept header explicitly contains application/xhtml+xml (with either no "q" parameter or a positive "q" value) deliver the document using that media type.
  2. If the Accept header explicitly contains text/html (with either no "q" parameter or a positive "q" value) deliver the document using that media type.
  3. If the accept header contains "/" (a convention some user agents use to indicate that they will accept anything), deliver the document using text/html.
like image 192
Grodriguez Avatar answered Feb 01 '26 01:02

Grodriguez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!