我正在使用Jersey的集成Jackson处理将传入的JSON转换为POJO,例如:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response newCustomer( CustomerRepresentation customer)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果客户端发送带有无效字段的JSON,则Jersey当前返回a 500 Internal Server Error.相反,我想返回一个400 Bad Request,最好有一些有意义的细节,表明哪些字段有误.
有关如何实现这一目标的任何见解?(至少返回一个通用的400而不是完全不合适的500?)
更新: 这是在调用我的处理程序之前在服务器端生成的异常:
javax.servlet.ServletException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "this_isnt_a_known"_field" (Class com.redacted....), not marked as ignorable
Run Code Online (Sandbox Code Playgroud) 非常直截了当的问题.我正在使用Jersey构建一个REST系统.如果我有一个具有值的类,我需要在处理期间使用但不希望在类被封送时作为XML或JSON输出的一部分发送,有没有办法忽略它?就像是:
@XmlRootElement(name="example")
class Example {
private int a;
private String b;
private Object c;
@XmlElement(ignore=true)
public int getA() { return a; }
@XmlElement
public String getB() { return b; }
@Ignore
public Object getC() { return c; }
... //setters, constructors, etc.
}
Run Code Online (Sandbox Code Playgroud)
我希望像ignore=trueover getA()或@Ignoreover 这样的东西getC()能起作用,但我找不到任何文档.
从Jersey 2.9开始,可以通过声明性链接为超媒体驱动的REST API创建链接关系.
这段代码,例如:
@InjectLink(
resource = ItemResource.class,
style = Style.ABSOLUTE,
bindings = @Binding(name = "id", value = "${instance.id}"),
rel = "self"
)
@XmlJavaTypeAdapter(Link.JaxbAdapter.class)
@XmlElement(name="link")
Link self;
Run Code Online (Sandbox Code Playgroud)
......理论上预计会产生这样的JSON:
"link" : {
"rel" : "self",
"href" : "http://localhost/api/resource/1"
}
Run Code Online (Sandbox Code Playgroud)
但是,Jersey会生成不同的JSON,其中包含许多我不需要的属性:
"link" : {
"rel" : "self",
"uri" : "http://localhost/api/resource/1",
"type": null,
"uriBuilder" : null
}
Run Code Online (Sandbox Code Playgroud)
另请注意href,它使用的是代替uri.我查看了Jersey Link对象的实现并找到了JerseyLink.
我想使用Jersey的声明性链接,而不是推出我自己的实现.我最终使用Jackson注释只是为了忽略其他JerseyLink属性.
@JsonIgnoreProperties({ "uriBuilder", "params", "type", "rels" })
Run Code Online (Sandbox Code Playgroud)
有没有人使用与Jersey的声明性链接并且具有预期的JSON输出(例如,href而不是uri没有额外的Jersey属性)而不必使用JsonIgnoreProperties或其他黑客?
谢谢. …
我正在使用JAX-RS我的网络服务.我有共同的功能,并希望使用继承.我提供简单的CRUD操作.我已经定义了这样的接口:
public interface ICRUD {
@POST
@Consumes("application/json")
@Produces("application/json")
@Path("create")
public String createREST(String transferObject);
@GET
@Consumes("application/json")
@Produces("application/json")
@Path("retrieve/{id}")
public String retrieveREST(@PathParam("id") String id);
@POST
@Consumes("application/json")
@Produces("application/json")
@Path("update")
public void updateREST(@Suspended final AsyncResponse asyncResponse,
final String transferObject) ;
@DELETE
@Consumes("application/json")
@Produces("application/json")
@Path("delete/{id}")
public String deleteREST(@PathParam("id") String id);
}
Run Code Online (Sandbox Code Playgroud)
我有一个实现此接口的抽象类:
public abstract class BaseREST implements ICRUD{
private final ExecutorService executorService = Executors.newCachedThreadPool();
@Override
public String createREST(String transferObject) {
return create(transferObject).toJson();
}
@Override
public String retreiveREST(@PathParam("id") String id) {
return retreive(id).toJson();
} …Run Code Online (Sandbox Code Playgroud) 我在下面给出了一个POJO,我希望将其作为JSON或XML输出到服务器.
这就是我所做的
客户:
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(getBaseURI());
public void putFriend(String uri , Friend friend)
{
System.out.println(friend.toString());
target = target.path(some_path).path(uri);
ClientResponse response = target.request(MediaType.APPLICATION_JSON).put(Entity.entity(friend,MediaType.APPLICATION_JSON),ClientResponse.class);
}
Run Code Online (Sandbox Code Playgroud)
我在网上找到的例子是使用WebResource.
我不知道如何使用WebTarget.我所做的是从在SO上找到的一些示例中获取,但Entity.entity()给出了错误未定义的方法实体(friend,String).
POJO
@XmlRootElement
public class Friend{
private String friendURI;
private String event;
private String uri;
String getUri() {
return uri;
}
void setUri(String uri) {
this.uri = uri;
}
String getFriendURI() {
return friendURI;
}
void setFriendURI(String friendURI) {
this.friendURI = friendURI;
}
String getEvent() { …Run Code Online (Sandbox Code Playgroud) 我试图了解DropWizard中的身份验证和授权是如何工作的.我已经阅读了他们的auth指南以及GitHub上的dropwizard-security项目,但感觉我仍然缺少一些重要的概念.
public class SimpleCredential {
private String password;
public SimpleCredential(String password) {
super();
this.password = password;
}
}
public class SimplePrincipal {
pivate String username;
public SimplePrincipal(String username) {
super();
this.username = username;
}
}
public class SimpleAuthenticator implements Authenticator<SimpleCredential, SimplePrincipal> {
@Override
public Optional<SimplePrincipal> authenticate(SimpleCredential credential) throws AuthenticationException {
if(!"12345".equals(credential.getPassword())) {
throw new AuthenticationException("Sign in failed.");
}
Optional.fromNullable(new SimplePrincipal("simple_user"));
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的Application子类中:
@Override
public void run(BackendConfiguration configuration, Environment environment) throws Exception …Run Code Online (Sandbox Code Playgroud) 我正在使用带有jackson提供程序的RestEasy客户端并收到上述错误
客户端代码是:
ClientRequest request = new ClientRequest(url);
request.accept(MediaType.APPLICATION_JSON);
ClientResponse<String> response = request.get(String.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
BufferedReader br =
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes())));
Run Code Online (Sandbox Code Playgroud)
response.getEntity()正在抛出ClientResponseFailure异常,错误是
Unable to find a MessageBodyReader of content-type application/json and type class java.lang.String
Run Code Online (Sandbox Code Playgroud)
我的服务器端代码如下:
@GET
@Path("/{itemId}")
@Produces(MediaType.APPLICATION_JSON)
public String item(@PathParam("itemId") String itemId) {
//custom code
return gson.toJSON(object);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Jersey Client来模拟对我的Web服务的HTTP请求.我试图从文档中实现这个简单的例子.这是我的简短代码:
public void restoreTest(String sessionId) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(idsUrl).path("restore");
Form form = new Form();
form.param("sessionId", sessionId);
target.request(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
}
Run Code Online (Sandbox Code Playgroud)
我甚至没有实现整个示例,因为目前我在最后一行得到一个异常:
java.lang.NoSuchMethodError: javax.ws.rs.core.MultivaluedMap.addAll(Ljava/lang/Object;[Ljava/lang/Object;)V
at org.glassfish.jersey.client.ClientRequest.accept(ClientRequest.java:254)
at org.glassfish.jersey.client.JerseyWebTarget.request(JerseyWebTarget.java:232)
at org.glassfish.jersey.client.JerseyWebTarget.request(JerseyWebTarget.java:60)
at org.icatproject.idsclient.TestingClient.restoreTest(TestingClient.java:112)
at org.icatproject.ids.ids2.ArchiveTest.restoreThenArchiveDataset(ArchiveTest.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) …Run Code Online (Sandbox Code Playgroud) 如何Map使用Jersey/JAX-RS框架将XML作为XML/JSON文档返回并不是那么明显.它已经支持Lists,但是当涉及到Maps时,则没有MessageBodyWriter.即使我要将其嵌入Ma到包装类中,mapXML模式中也没有类型.
关于如何将Map编组到Jersey中的XML/JSON文档的任何实用建议?
我想在球衣休息服务中抓住所有意想不到的例外情况.因此我写了一个ExceptionMapper:
@Provider
public class ExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {
private static Logger logger = LogManager.getLogManager().getLogger(ExceptionMapper.class.getName());
@Override
public Response toResponse(Exception e) {
logger.log(Level.SEVERE, e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal error").type("text/plain").build();
}
}
Run Code Online (Sandbox Code Playgroud)
映射器捕获所有异常.所以我写不出来:
public MyResult getById(@PathParam("id")) {
if (checkAnyThing) {
return new MyResult();
}
else {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
Run Code Online (Sandbox Code Playgroud)
这是由Mapper捕获的.现在我要写:
public Response getById(@PathParam("id") {
if (checkAnyThing) { {
return Response.ok().entity(new MyResult()).build();
}
else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
Run Code Online (Sandbox Code Playgroud)
这是捕获所有意外异常并正确返回错误(错误代码)的正确方法吗?或者还有其他(更正确的)方式吗?
jax-rs ×10
java ×7
jersey ×7
rest ×4
jersey-2.0 ×3
annotations ×1
client ×1
dropwizard ×1
inheritance ×1
jackson ×1
jaxb ×1
json ×1
resteasy ×1