本文介绍了使用Jersey 2的REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Jersey 2实现REST API,我希望将资源分成接口和它们的实现,例如:

I would like to implement a REST API using Jersey 2 and I would like to have resources separated into interfaces and their implementations like e.g.:

@Path("hello")
public interface HelloLogic {
    @GET
    @Produces("application/json")
    public String hello();
}

public class HelloLogicResource implements HelloLogic {
    public String hello() {
        return "{\"reply\": \"Hello\"}";
    }
}

我没有任何运气来获取资源。对于刚刚提到的hello资源,我希望以下内容足够:

I do not have any luck getting the resources exposed though. For the hello resource just mentioned I was hoping that the following would be enough:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(new MyApplicationBinder());
    }
}

public class MyApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(HelloLogic.class).to(HelloLogicResource.class);
    }
}

web.xml:

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>stines.api.MyApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>MyApplication</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

pom.xml:

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.4.1</version>
</dependency>

但是点击

http://localhost:8080/hello

我收到404回复:

输入将不胜感激:)谢谢。

Input will be greatly appreciated :) Thanks.

新发现:它适用于此:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        registerClasses(HelloLogicResource.class);
    }
}


推荐答案

这工作:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        registerClasses(HelloLogicResource.class);
    }
}

这篇关于使用Jersey 2的REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:21