arthur
arthur

Reputation: 3325

Rest | @Produces and @Consumes : why dont they both get called for same MIME-type

a newbie in JAX-REST (jersey 1.8 impl)

I have a class for Resource "/hello"

package com.lbs.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class Test {


    //-- produces MIME type text/plain
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public  String thankYouTxt(){
        System.out.println("thankYouTxt");

        return "thankYouTxt\n";
    }

    //-- consumes MIME type text/plain
    @GET
    @Consumes(MediaType.TEXT_PLAIN)
    public String thankYouInputTxt(){
        System.out.println("thankYouInputTxt");
        return "thankYouInputTxt";

    }


    //-- produces MIME type text/html
    @GET
    @Produces(MediaType.TEXT_HTML)
    public  String thankYouHTML(){
        System.out.println("thankYouHTML"); 
        return "thankYouTxtHTML";
    }


    //-- consumes MIME type text/html
    @GET
    @Consumes(MediaType.TEXT_HTML)
    public  void thankYouInputHTML(){
        System.out.println("thankYouInputHTML");
        //return "thankYouInputHTML";
    }



    //-- produces MIME type text/xml 
    @GET
    @Produces(MediaType.TEXT_XML)
    public  String thankYouXML(){
        System.out.println("thankYouXml");
        return "<?xml version=\"1.0\"?> <message>thankYouTxt</message>";
    }
    //-- consumes MIME type text/xml    
    @GET
    @Consumes(MediaType.TEXT_XML)
    public String thankYouInputXML(){
        System.out.println("thankYouInputXML");
        return "thankYouInputXML";
    }



}

when I sent a request with a header Content-Type : text/html, I would expect both the @Produces and @Consumes annotated methods thankYouHTML() and thankYouInputHTML() to be called.

but only the @Produces thankYouHTML() method get called? why? why is not the @Consumes annotated method thankYouHInputTML() also called?

Upvotes: 0

Views: 17317

Answers (1)

pWoz
pWoz

Reputation: 1679

You should remember that:

  1. Only one method is executed for a single request. So it is impossible to execute two methods (or more) in single request;
  2. JAX-RS runtime decides which one method should be executed according to request header values sent to to the server.

JAX-RS runtime tries to match:

  • http method (GET,POST, ...) with proper annotation (@GET, @POST,...);

  • request path ('/api/something') with the proper @Path annotation;

  • http content-type header (link) with proper @Consumes annotation;

  • http accept header with propper @Produces annotation;

So (for example) @Produces annotation does not denote that annotated method produces something. It denotes that method will be executed when matching accept header will be contained in request.

If You need more information abou RestFull webservices i advice You to read these resources:

Upvotes: 7

Related Questions