标签: jax-rs

如何使用jax-rs子资源定位器处理持久化上下文(EntityManager)?

我在我的应用程序中使用jax-rs restful web服务和子资源定位器.但是,在将entityManager传递给子资源后,我无法在此子资源中保留任何新对象.

然而,entityManager让我可以查询数据.

这是我的主要资源:

@Path("/registrations")
@Stateless
public class RegistrationsResource {

    @Context
    private UriInfo context;

    @PersistenceContext(unitName="pctx")
    private EntityManager em;

    public RegistrationsResource() {
    }

    //POST method ommited

    @Path("{regKey}")
    public RegistrationResource getRegistrationResource(@PathParam("regKey")
    String regKey) {
        return RegistrationResource.getInstance(regKey, em);
    }
Run Code Online (Sandbox Code Playgroud)

}

这是我的子资源:

public class RegistrationResource {

    private String regKey;
    private EntityManager em;

    private RegistrationResource(String regKey, EntityManager em) {
        this.regKey = regKey;
        this.em = em;
    }

    @Path("securityQuestion")
    @GET
    public String getQuestion() {
        return "iamahuman"+regKey;
    }

    @Path("securityQuestion")
    @POST
    public void postSecurityAnswer(String answer) {
        if(!answer.equals("iamahuman"+regKey)){
            throw …
Run Code Online (Sandbox Code Playgroud)

java rest jpa jax-rs

4
推荐指数
2
解决办法
4482
查看次数

从JAX-RS servlet动态创建映像

是否可以创建PNG图像并将其作为JAX-RS资源的一部分直接输出到浏览器?

像这样的东西:

@Path("img/{externalId}")
@Stateless
@Produces({"image/png"})
public class MyImgResource {

  @GET
  public Response (@PathParam("externalId") String externalId) {
    // create image, write to buffered output stream

    return Response.ok().entity(stream).build();
  }
}
Run Code Online (Sandbox Code Playgroud)

这会有用吗?我是否必须处理正确的标题(Content-Type),还是由@Produces注释完成?可以输出图像作为Response?我可以Response从流中构建一个?

java image jax-rs dynamic-image-generation

4
推荐指数
1
解决办法
6493
查看次数

我可以让Jersey在全局/默认情况下使用自然JSON表示法吗?

我正在使用Jersey为服务构建REST API.我希望能够接受并返回JSON和XML,并且主要使用它,但我不喜欢Jersey喜欢吐出的JSON的默认"映射"风格.

我知道更新的"自然"符号(来自http://jersey.java.net/nonav/documentation/latest/json.html,我会详细引用它,因为它显然存在默认"映射"的问题符号):

在使用映射的JSON表示法一段时间后,很明显,需要手动配置所有各种事情可能有点问题.为了避免手动工作,在Jersey版本1.0.2中引入了一种新的,自然的JSON表示法.使用自然符号,Jersey会自动确定需要处理的各个项目,因此您无需进行任何类型的手动配置.Java数组和列表映射到JSON数组,即使对于单元素情况也是如此.Java数字和布尔值正确映射到JSON数字和布尔值,你不需要打扰XML属性,就像在JSON中一样,它们保留原始名称

并且想在任何地方使用它,但我无法弄清楚如何使用它.我通过Tomcat的XML配置文件实例化/配置Jersey - 使用我认为是与servlet/servlet-class/init-param标签的正常舞蹈 - 但是我无法找到关于它是否或如何的文档可以从那里指定JSONConfiguration选项.

我也尝试实现自己的ContextResolver,它应用了我从Java代码实例化的JSONJAXBContext,我可以在其中应用JSONConfiguration.natural()(这个例子就像这个答案).这是有效的,但仅适用于我在该代码中明确列出的类型,并传递给JSONJAXBContext构造函数.这个额外的代码不仅可以编写和维护,而且如果我添加更多的数据类也会更改,但它不适用于像List这样的东西.

有没有办法告诉泽西岛只使用自然符号而不是映射符号,总是和所有类型?

java json jax-rs jersey

4
推荐指数
1
解决办法
2888
查看次数

在启用内容类型协商时,JAXRS休息服务是否容易受到CSRF攻击?

我有一个RESTful API,其注释类似@Consumes(MediaType.JSON) - 在这种情况下,CSRF攻击是否仍然可以在这样的服务上进行?我一直在修补我在服务器端使用CSRFGuard保护我的服务,或者从客户端进行双重提交.但是,当我尝试使用带有enctype ="text/plain"的FORM来发送请求时,它不起作用.这里解释这种技术.如果我在使用注释中有MediaType.APPLICATION_FORM_URLENCODED,则此方法有效.当我使用POST/PUT/DELETE谓词时,内容协商非常有用,但GET仍然可以访问,可能需要查看.

任何建议或输入都会很棒,如果您需要更多信息,请告诉我.

干杯

rest web-services jax-rs csrf

4
推荐指数
1
解决办法
2106
查看次数

强制glassfish 4使用杰克逊2.3

我写了一个应该在Glassfish 4上运行的maven应用程序.

标准ApplicationConfig如下所示:

@javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        // following code can be used to customize Jersey 2.0 JSON provider:

        try {
           Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");

        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        addRestResourceClasses(resources);
        return resources;
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是,我生成Json的资源应该使用jackson 2.3注释.但我的glassfish使用了一些codehaus....包提供json.codehaus是杰克逊的旧版本.我想使用来自fastxml的新文件,它提供@JsonIdentityInfo注释.

我以为我可以写下来解决我的问题:

@javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();

        resources.add(JacksonFeatures.class);  //from the com.fasterxml.jackson.jaxrs.annotation Package
        resources.add(JacksonJaxbJsonProvider.class);
        resources.add(JacksonJsonProvider.class);

        addRestResourceClasses(resources);
        return …
Run Code Online (Sandbox Code Playgroud)

glassfish jax-rs jersey jackson java-ee-7

4
推荐指数
1
解决办法
8995
查看次数

JAXRS客户端找不到邮件正文编写器

我有一个像这样配置的jaxrs客户端:

<jaxrs:client id="opaRestProxy" name="opaRestProxy"
        address="${endpoint}" serviceClass="com.test.RestProxy"
        inheritHeaders="true" threadSafe="true">
        <jaxrs:headers>
            <entry key="Accept" value="application/json" />
            <entry key="Content-Type" value="application/json" />
        </jaxrs:headers>
    </jaxrs:client>
Run Code Online (Sandbox Code Playgroud)

但是当我发送请求时,我得到以下异常:

Caused by: org.apache.cxf.interceptor.Fault: .No message body writer has been found for class : class com.test.RequestObject, ContentType : application/json.
    at org.apache.cxf.jaxrs.client.ClientProxyImpl$BodyWriter.handleMessage(ClientProxyImpl.java:646)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
    at org.apache.cxf.jaxrs.client.ClientProxyImpl.doChainedInvocation(ClientProxyImpl.java:527)
    ... 47 more
Run Code Online (Sandbox Code Playgroud)

我的RestProxy类看起来像这样:

@Component
public interface RestProxy {

  @POST
  @Path("/getSomething")
  String getSomething(RequestObject RequestObject);
}
Run Code Online (Sandbox Code Playgroud)

java json cxf jax-rs

4
推荐指数
1
解决办法
1万
查看次数

REST Java客户端API:在分配另一个之前释放连接

我正在使用以下测试代码调用REST服务:

public class TestRESTServices {
    private static final String BASE_URL = "http://localhost/ma.ge.persistence-1.0/rest/reference";
    private static URI uri = UriBuilder.fromUri(BASE_URL).port(8080).build();
    private static Client client = ClientBuilder.newClient();

    @Test
    public void createAndDeleteAReference() {

        Reference r = ReferenceFactory.createReference("Maz",
                "dummy", 1.7);
        Response response = client.target(uri).request().post(Entity.entity(r, MediaType.APPLICATION_JSON));
        assertEquals(Response.Status.CREATED, response.getStatusInfo());

        URI referenceURI = response.getLocation();

        // Get the posted reference
        response = client.target(referenceURI).request().get();

        Reference retreivedRef = response.readEntity(Reference.class);
        assertEquals(Response.Status.OK, response.getStatusInfo());
        assertEquals(retreivedRef.getName(), r.getName());

    }
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

在分配另一个之前,请确保释放连接。在org.apache.http.impl.conn.BasicClientConnectionManager $ 1.getConnection(BasicClientConnectionManager.java:139)在org.apache.http.impl.conn.BasicClientConnectionManager.java:162在org.apache.http。在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)处的impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)在org.apache.http.impl.client.AbstractHttpClient.execute( org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)上的AbstractHttpClient.java:805)...还有26个

java rest jax-rs

4
推荐指数
1
解决办法
6274
查看次数

Jax-RS没有使用@provider注释注册资源

我使用jersey api在weblogic 12c中运行了一个rest应用程序.我有一个带有注释@provider的http请求过滤器类.但是,在部署应用程序时,过滤器类未向我在ApplicationConfig类中添加的其他资源类注册.然后我无法过滤http请求.下面是我的日志和代码

Sep 01, 2015 11:16:12 AM weblogic.jaxrs.server.portable.servlet.JerseyServletContainerInitializer onStartup
INFO: Number of JAX-RS specific classes to be examined:24
Sep 01, 2015 11:16:12 AM weblogic.jaxrs.server.portable.servlet.BaseServletContainerInitializer addServletWithApplication
INFO: Registering the Jersey servlet application, named com.ws.rest.ApplicationConfig, at the servlet mapping, /rest/*, with the Application class of the same name
Sep 01, 2015 11:16:12 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18.1 02/19/2014 03:28 AM'
Sep 01, 2015 11:16:12 AM com.sun.jersey.server.impl.application.DeferredResourceConfig$ApplicationHolder <init>
INFO: Instantiated the Application class com.ws.rest.ApplicationConfig
Sep 01, 2015 …
Run Code Online (Sandbox Code Playgroud)

java rest weblogic jax-rs jersey

4
推荐指数
2
解决办法
4329
查看次数

在ClientRequestFilter中附加查询参数

我只需要将查询参数附加到传出请求上.(Java EE 7.0,JAX-RS 2.0)

具体来说,我目前使用RESTeasy Client ver 3.0.14,所以我使用花哨的接口代理系统进行调用.我试图产生这样的东西:

myapplication/api/path?timestamp=000

有:

@Provider
public class MyRequestFilter implements ClientRequestFilter {

    @Context
    private HttpServletRequest servletRequest;

    public void filter(ClientRequestContext requestContext) throws IOException {

        servletRequest.getParameterMap().put("timestamp", new String[]{
                String.valueOf(new Date().getTime())
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

我确定我也在注册它client.register(MyRequestFilter.class).随意问的问题.谢谢!

java jax-rs java-ee resteasy java-ee-7

4
推荐指数
1
解决办法
832
查看次数

Spring Boot + Jersey类型过滤器-对服务的错误请求400消耗MULTIPART_FORM_DATA

我正在使用Spring Boot v1.5.10 + Jersey v2.25.1,将jersey配置为过滤器来访问静态文件夹文件。我收到HTTP响应400错误的服务消耗请求MULTIPART_FORM_DATA

提议将Jersey配置为过滤器。

spring.jersey.type=filter
Run Code Online (Sandbox Code Playgroud)

如果我删除了上述属性,即使用Jersey作为Servlet,则该服务正在运行,但无法访问静态文件夹。

这是控制器,

@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public ResponseBean save(
        @FormDataParam("fileToUpload") InputStream file,
        @FormDataParam("fileToUpload") FormDataContentDisposition fileDisposition,
        @FormDataParam("fromData") FormDataDto data) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

编辑:

GitHub链接https://github.com/sundarabalajijk/boot-jersey

启动应用程序时, spring.jersey.type=filter

http:// localhost:8080 /(有效)

http:// localhost:8080 / hello.html(有效)

http:// localhost:8080 / save(不起作用)-使用的邮递员。

什么时候 spring.jersey.type=servlet

http:// localhost:8080 /(有效)

http:// localhost:8080 / hello.html(无效)

http:// localhost:8080 / save(有效)

邮递员要求

file-upload jax-rs servlet-filters jersey-2.0 spring-boot

4
推荐指数
1
解决办法
995
查看次数