问题描述
JAX-REST的新手(球衣1.8版本)
a newbie in JAX-REST (jersey 1.8 impl)
我有一个资源"/hello"类
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";
}
}
当我发送带有标头Content-Type : text/html
的请求时,我希望同时调用@Produces
和@Consumes
注释的方法thankYouHTML()
和thankYouInputHTML()
.
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.
但是只有@Produces thankYouHTML()
方法会被调用吗?为什么?为什么不同时调用@Consumes
带注释的方法thankYouHInputTML()
?
but only the @Produces thankYouHTML()
method get called? why? why is not the @Consumes
annotated method thankYouHInputTML()
also called?
推荐答案
您应该记住:
- 对于单个请求仅执行一种方法.因此,不可能在单个请求中执行两个(或多个)方法;
- JAX-RS运行时根据发送到服务器的请求标头值来决定应执行哪种方法.
JAX-RS
运行时尝试匹配:
-
http方法(
GET
,POST
,...)带有正确的注释(@GET
,@POST
,...);
http method (
GET
,POST
, ...) with proper annotation (@GET
,@POST
,...);
请求路径('/api/something'
);
http content-type
标头(链接)带有正确的@Consumes
注释;
http content-type
header (link) with proper @Consumes
annotation;
http accept
标头,带有适当的@Produces
注释;
http accept
header with propper @Produces
annotation;
因此(例如)@Produces
注释并不表示带注释的方法会产生某些结果.它表示当请求中包含匹配的accept header
时将执行该方法.
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.
如果您需要RestFull Web服务的更多信息,我建议您阅读以下资源:
If You need more information abou RestFull webservices i advice You to read these resources:
这篇关于休息| @Produces和@Consumes:为什么不都为相同的MIME类型调用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!