问题
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?
回答1:
You should remember that:
- Only one method is executed for a single request. So it is impossible to execute two methods (or more) in single request;
- 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:
rfc2616
RESTful Java with JAX-RS - By Bill Burke
来源:https://stackoverflow.com/questions/17148529/rest-produces-and-consumes-why-dont-they-both-get-called-for-same-mime-typ