Search code examples
javahtmlservletstypesresponse

How to format servlet response to produce media types acceptable by "accept" parameter in HTML?


I want to understand how the response to browsers works. As an example, jersey says it responds a request with most acceptable media type defined by annotation @Produces:

 @GET
 @Produces({"application/xml", "application/json"})
 public String doGetAsXmlOrJson() {
   ...
 }

In the case above, the most acceptable type is "application/xml". Well... For this media type, I would do in Servlet:

response.setContentType("application/xml");
PrintWriter out = response.getWriter();
out.println("<root><x>1</x></root>");

The point is: I need to format the response according to the media type, as I done above in last line.

I want to know how to format, using HttpServletResponse, the second acceptable type, supposing browser doesn't support "application/xml". In this situation, "application/json" should be chosen.


Solution

  • You can't know what media type the client supports unless it tells you. This is usually done with the Accept header.

    The Accept request-header field can be used to specify certain media types which are acceptable for the response.

    So if the client sends

    Accept: application/xml
    

    You should try to produce an application/xml formatted response.

    String mediaType = request.getHeader("Accept"); // can return null
    

    If you can't produce such a response, you should respond with a 406 Not Acceptable status code with an appropriate body.