开发者

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, 开发者_如何学Pythonresponse);
    }
}

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


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.


text/xhtml is not a valid content type so your browser won't know how to render it properly.

For XHTML 1.0 the content type is supposed to be text/html http://www.w3.org/TR/xhtml-media-types/#compatGuidelines (See point A.9)

Edit:

This is a better link that specifically discusses XHTML and its various allowed Content-Type's

http://www.w3.org/International/articles/serving-xhtml/


Either:

  1. When you say set the content-type to xhtml you mean literally xhtml or text/xhtml — in which case the problem is that the content type for XHTML is application/xhtml+xml
  2. You are using Internet Explorer 8 or lower, which doesn't support XHTML. Support is being added in IE9 and is only available if you are using the beta.


Its method that take string parameter and returns nothing.

response.setContentType("text/html");

here "text" is type and html is subtype.

setContentType() method sets the content type of "response being delivered", when response is not yet sent over. You can say for css:

response.setContentType("text/css");


Isn't it basic browser feature?

If browser know the file format(like html or xml or text ..) it will display the contents directly on the browser

Otherwise, it tries to save it or open with other application

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜